简体   繁体   中英

How to place an image icon at the exact touch location in android

I am placing an icon on my screen in my android app on the first touch. I have been able to implement the same, but my question is regarding how the position of this image can be.

When i use a factor of 20 and use the following code in side my onTouch event,

Bitmap img = BitmapFactory.decodeResource(Res, R.drawable.myPoint);
canvas.drawBitmap( img,  vec.get(i).x - 20, vec.get(i).y - 20, null);

The image seems to be superimposed on the point of my touch (i am not sure which coordinates). And the output looks like this 在此处输入图片说明

When i do not use any factor and use the following code

      Bitmap img = BitmapFactory.decodeResource(Res, R.drawable.myPoint);
       canvas.drawBitmap( img,  vec.get(i).x , vec.get(i).y , null);

The image seems to be placed slightly away from the point of touch as seen here. 在此处输入图片说明

My aim is to have the pointed tip of the image(on the right) correctly point to the exact coordinates where the touch happened so that i can shoot out a path from there to the next click position like this. 在此处输入图片说明

Will this require measuring the dimensions ie width and height of the image to place the image at the required location.How does android place such large images by default with respect to a normal small touch point. Is the centroid of the image taken into consideration?

The x and y arguments of drawBitmap refer to the top left corner of the bitmap.

Here would be the proper (x, y) coordinates if there is no border around the image you gave (assuming it is symmetric along the x-axis):

x = touchX - bitmapWidth;
y = touchY - bitmapHeight/2;

Measure the Bitmap you're drawing, then add those values to the draw coordinates.

canvas.drawBitmap(img, vec.get(i).x + (img.x / 2), vec.get(i).y + img.y, null)

That code should give you an idea of what to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM