4

我正在尝试top right hand cornerCanvas

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

//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.
}

有人可以帮我吗?

4

1 回答 1

3

在 Rect bitmapRect 下的 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 的绘图命令时,一个是你要绘制的源,一个是目标将在哪里绘制

于 2013-09-13T03:21:26.157 回答