【问题标题】:how to draw a Bitmap on the Top Right of the Canvas如何在画布的右上角绘制位图
【发布时间】:2013-09-13 02:30:17
【问题描述】:

我正在尝试在Canvastop right hand corner 上绘制位图

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

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

有人可以帮我吗?

【问题讨论】:

  • 在绘制位图中你有油漆的地方放 null
  • 我试过了,但它只翻转了图像,但没有覆盖右上角
  • 对于您的 bitmapRect,它显示 canvasWidth - 200,使用您放入画布宽度的原始位图 - 不管怎样,试试吧
  • 位图被翻转是负数的结果
  • 查看我的答案,我不知道您使用的是视图,我认为当您的代码未启动时它只是一个常规画布,这就是您扩展视图的方式

标签: java android bitmap android-canvas rect


【解决方案1】:

在 MyView 的 Rect bitmapRect 下;制作变量

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 使用绘图命令时,一个是你要绘制的源,一个是将要绘制的目的地

【讨论】:

  • 还是同样的问题=(它覆盖了左上角的区域但不覆盖右上角
  • 看到我刚刚更改了 bitmapRect
  • 这样,我又坏了
  • 不知道为什么会这样。我想知道是否有另一种方法可以在 x,y 位置绘制位图并测试motionevent的边界
  • 我把 rect 弄错了,我怎么弄的(width-200,0,200,50)是错的,我刚刚把它放上去是正确的,它应该是你要找的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2011-12-28
相关资源
最近更新 更多