在图像上的接触点(坐标)处绘制矩形或形状

时间:2012-09-03 11:17:36

标签: android drawable

如何在触摸点绘制矩形(使用形状资源)(如坐标28,87)。我创造了一个像这样的形状。

android:shape="rectangle" >


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

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

这个矩形我想在图像上的触摸点绘制。

2 个答案:

答案 0 :(得分:3)

您可以在该视图的onDraw()方法上在视图上绘制形状。没有可用于在视图画布上绘制可绘制形状的方法。
而且您不必使用可绘制的形状来绘制矩形。您可以使用canvas.drawRect()方法绘制一个矩形。 这是一个代码:

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;
}

}

答案 1 :(得分:2)

我想,

@kam'解决方案需要更新。构造函数中的所有内容都必须在init()方法中,并且构造函数必须被覆盖3次。

公共类MyView扩展了View {

private float xDown = 0,yDown = 0, xUp = 0, yUp = 0;

Paint mPaint;

boolean touched = false;
public MyView(Context context) {
    super(context);
    init(context);
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public MyView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context);
}

private void init(Context context) {
    mPaint = new Paint();
    mPaint.setColor(Color.BLUE);
    mPaint.setStyle(Paint.Style.STROKE);
}

@Override
protected void onDraw (Canvas canvas)  {
    canvas.drawColor(Color.TRANSPARENT);
    if(touched) {
        canvas.drawRect(xDown, yDown, xUp, yUp, mPaint);

    }
}

@Override
public boolean onTouchEvent (MotionEvent event) {
    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            xDown = event.getX();
            yDown = event.getY();

            xUp = 0;
            yUp = 0;
            break;
        case MotionEvent.ACTION_MOVE:
            xUp = event.getX();
            yUp = event.getY();
            touched = true;
            break;
        case MotionEvent.ACTION_UP:
            xUp = event.getX();
            yUp = event.getY();
            touched = true;
            break;
    }
    invalidate();
    return true;
}

}