Drawing on a canvas in OnTouchListener

Drawing on a canvas in OnTouchListener



I try to draw a line with finger move on an ImageView with a bitmap inside using the setOnTouchListener() method.



Here is the code.


@Override
public boolean onTouch(View view, MotionEvent event)
int action = event.getAction();
switch (action)
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
photoView.invalidate();
break;
case MotionEvent.ACTION_UP:
canvas.drawBitmap(notChangedRotatedBitmap, new Matrix(), paint);
photoView.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;

return true;



The problem is that it lookes like the coordinates returned by the event object is multiplied by 2, because if I start my finger move near the left top corner it starts almost below my finger, but when I move my finger away from the top left corner the line begin to grow much faster then my move (near two times faster) and soon goes over the borders of the view.
On the other hand, if I start my finger move near the right bottom corner it just don't show until I cross the center of the image moving towards the left top corner.



UPD>
Besides, I use this attributes on Imageview:


android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"





Is canvas a field of your activity? How to you initialize it?
– Michael
Aug 27 '13 at 21:52






I initialize the canvas at the field private Canvas canvas = new Canvas(); and then canvas.setBitmap(rotatedBitmap); on the touch start. Really this line with setBitmap goes after the 3rd line of the provided code.
– TpoM6oH
Aug 28 '13 at 14:01





1 Answer
1



It seems, that the bitmap you draw on is not the same size as the ImageView. So you paint on the bitmap using the event coordinates and when the bitmap is displayed, it's scaled to a different size due to the scaleType="fitCenter" attribute.


scaleType="fitCenter"



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)