Draw circle where user touches screen

2019-08-11 22:04发布

问题:

I draw a circle where the user touches a image view. It draws the circle fine, but it is not where the user touches. It is always off the left by a lot. Here is the code:

getting the touch:

image.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View arg0, MotionEvent arg1) {
        System.out.println("Touch recieved at "+arg1.getX() + " " + arg1.getY());
        touchX =  (arg1.getX());
        touchY =   (arg1.getY());
        System.out.println("Touch recieved at "+touchX + " " + touchY);
        image.setImageBitmap(createImage());

        return true;
    }
});

and drawing on the image:

public Bitmap createImage(){
        Bitmap image = bmp.copy(Bitmap.Config.RGB_565, true);
        Canvas canvas = new Canvas(image);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.GREEN);
        canvas.drawCircle(touchX, touchY, radius, paint);
        System.out.println("Drew a circle at "+touchX+" " + touchY+" with a radius of "+radius+".");
        return image;
    }

Any ideas?

回答1:

Try to draw at

touchX=touchX- image.getWidth() / 2;
touchY=touchY- image.getHeight() / 2;

this will draw the center of the image the place you touch



回答2:

You have to add touch listener to the layout not to the image. Add setOnTouchListener to the layout. No need of touch listener to the image.



回答3:

Have a look at Hello circle example