URAndroid URAndroid - 10 months ago 81
Android Question

Draw a Rectangle or Shape at Touch Point(Co-Ordinates) on the Image

How to Draw a rectangle (Using Shape Resources) at the touched point(like coordinates 28,87). I have Created a shape Like This.

android:shape="rectangle" >


android:color="@color/green" />

This rectangle I want to Draw at the touch point on the image.

Answer Source

You can draw a shape on a view in the onDraw() method of that view. There is no method available for drawing a shape drawable on a view canvas.
And you don't have to use a shape drawable for drawing a rectangle. You can draw a rectangle using canvas.drawRect() method. Here is a code for this:

public class MyView extends View{

float x,y;
Bitmap bmp;
Paint mPaint;
float width = 100.0f;
float height = 50.0f;

boolean touched = false;

public MyView (Context context)
    x = y = 0;
    mPaint = new Paint();

protected void onDraw (Canvas canvas)
        canvas.drawRect(x, y, x+width, y+height, mPaint);


public boolean onTouchEvent (MotionEvent event)
    touched = true;
    //getting the touched x and y position
    x = event.getX();
    y = event.getY();
    return true;