0
votes

I use canvas to draw on a bitmap and set the bitmap covered on an imageView.

I have draw a basic drawing in the method called drawGraph(), when user touches in the canvas I have to draw a circle there, for that I have used canvas inside onTouchEvent() method,it is not drawing anything there, the code is given below, what is the problem and how can I resolve this.

I also tried to create another bitmap with a straight line on it, set the new bitmap to imageView at the end of drawGraph() and checkClicked(). It shows that the new bitmap(with a straight line drawn) is correctly set to imageView at the start , but when click on the imageView a blank bitmap(not being drawn a straight line) is set to imageView. So I am sure that is canvas draw does't work in checkClicked().

Thanks for helping me in advance!

ImageView imageView;

Paint p = new Paint();
Bitmap myBitmap;
Bitmap workingBitmap;
Bitmap mutableBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_drawpanel);
    workingBitmap = Bitmap.createBitmap(myBitmap);
    mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);

    imageView = (ImageView) findViewById(R.id.image1);

    imageView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            int touchX = (int) (event.getX() + imageView.getX());
            int touchY = (int) (event.getY() + imageView.getY());

            checkClicked(touchX, touchY);

            return true;
        }
    });

    drawGraph();
}

public void drawGraph(){

    p.setAntiAlias(true);
    p.setColor(Color.BLACK);
    p.setStyle(Style.FILL_AND_STROKE);
    p.setStrokeWidth(5);

    Canvas canvas = new Canvas(mutableBitmap);

    //basic drawing is successfully drawn here

    imageView.setAdjustViewBounds(true);
    imageView.setImageBitmap(mutableBitmap);

}

public void checkClicked(int x, int y){

    p.setAntiAlias(true);
    p.setColor(Color.RED);
    p.setStyle(Style.FILL_AND_STROKE);

    Canvas canvas = new Canvas(mutableBitmap);

    //canvas doesn't draw a circle here
    canvas.drawCircle(x, y, 10, p);

    imageView.setAdjustViewBounds(true);
    imageView.setImageBitmap(mutableBitmap);
1

1 Answers

0
votes

It is being drawn, but drawn at a wrong position. Because the coordinates in the view are not the same as the coordinates in the bitmap.

You can verify it by starting to touch from the imageView and dragging your finger towards the top-left part of the screen.

You will need to get the scale and translation of the screen and imageview and convert the coordinates before drawing.

You can use imageView.getImageMatrix() to get the drawing matrix of the imageView which contains transformation of the image and do the math accordingly.