Question

I am trying to draw a bitmap on top right hand corner of the Canvas

So far I have done the following:

//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);

The problem is that when I run the app, the bitmap doesn't appear on the screen. Full code:

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

Can someone help me here please?

Was it helpful?

Solution

in MyView right under Rect bitmapRect; make the variables

public int width;
public int height;

then in your MyView class put this method in there

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

now you have the width and height of the canvas that you are using then in your onDraw() method make the bitmapRect like this

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

i think the problem is that how you had it you had a negative number in your rect and it was inverting the bitmap, when you use a draw command with Rects, one is the source of what your going to draw and one is the destination of where its going to be drawn

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top