URAndroid URAndroid - 1 month ago 18
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" >


<solid
android:color="@color/transparent"/>
<stroke

android:width="3dp"
android:color="@color/green" />




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

Answer

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)
{
    super(context);
    x = y = 0;
    mPaint = new Paint();
    mPaint.setColor(Color.BLUE);
    mPaint.setStyle(Style.STROKE);
}

@Override
protected void onDraw (Canvas canvas)
{
    canvas.drawColor(Color.WHITE);
    if(touched)
    {
        canvas.drawRect(x, y, x+width, y+height, mPaint);

    }   
}

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

}