如何在画布的右上角绘制位图

时间:2013-09-13 02:30:18

标签: java android bitmap android-canvas rect

我正在尝试在top right hand corner

Canvas上绘制位图

到目前为止,我已完成以下工作:

//100x40 dimensions for the bitmap
bitmap = BitmapFactory.decodeResource(getResources(),
                        R.drawable.backbutton);

Rect source = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
Rect bitmapRect = new Rect(0, 0, canvasWidth -200,50);

canvas.drawBitmap(bitmap, source, bitmapRect, paint);

问题是当我运行应用程序时,位图不会出现在屏幕上。 完整代码:

public class MyView extends View {
Rect bitmapRect;
public MyView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);    //To change body of overridden methods use File | Settings | File Templates.

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.backbutton);

    Rect source = new Rect(0,0,bitmap.getWidth(), bitmap.getHeight());
    bitmapRect = new Rect(0,0, bitmap.getWidth(), bitmap.getHeight());

    canvas.drawBitmap(bitmap, source, bitmapRect, new Paint());

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int)event.getX();
    int y =   (int)event.getY();
    if(null != bitmapRect && bitmapRect.contains(x,y)){
        Toast.makeText(view.getContext(), "this works", Toast.LENGTH_LONG).show();
    }


    return super.onTouchEvent(event);    //To change body of overridden methods use File | Settings | File Templates.
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

的RectbitRect下的MyView中;制作变量

public int width;
public int height;

然后在你的MyView类中将此方法放在那里

@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh)
{
width = w;
height = h;
}

现在您拥有正在使用的画布的宽度和高度 然后在你的onDraw()方法中使bitmapRect像这样

bitmapRect = new Rect(width -200,0, width, 50);

我认为问题在于如何使用你的矩形中有一个负数并且它反转了位图,当你使用带有Rects的绘图命令时,一个是你要绘制的内容的来源,一个是它将被绘制的目的地