简体   繁体   中英

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"

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.

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