How to draw a bitmap in the upper right of the canvas

I'm trying to draw a bitmap on top right hand corner 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 the application starts, the bitmap does not 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?

+4
source share
1 answer

in MyView, right under the Rect bitmapRect; make variables

 public int width; public int height; 

then in your MyView class put this method 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 use then in your onDraw () method do a bitmapRect as follows

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

I think the problem is that you had a negative number in your rectangle, and that was inverting the bitmap when you use the draw command with Rects, one of them is the source of what you are going to draw, and one is the destination where will be drawn

+3
source

Source: https://habr.com/ru/post/1501974/


All Articles