2

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

android:shape="rectangle" >


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

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

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

4

2 回答 2

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

}

于 2012-09-03T12:18:12.913 回答
2

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

公共类 MyView 扩展视图 {

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

}

于 2016-11-03T11:07:25.143 回答