如何在Imageview上绘制一个黑色边框和背景透明的矩形?

alf*_*ibg 4 android canvas paint draw imageview

我想在 ImageView 上绘制一个矩形作为下面的图片(黑色边框和透明作为背景)。基本上我下载一个图像,放在一个 ImageView 中,然后我收到 4 个点来绘制一个矩形。提前致谢

在此处输入图片说明

Vas*_*las 5

您的android.view.InflateException问题可以通过从 DrawView 类中删除构造函数并再次自动生成它们来解决。现在对于矩形,您必须具有类似这样的 onDraw:

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    paint.setColor(Color.TRANSPARENT);
    paint.setStyle(Paint.Style.FILL);
    float leftx = 50;
    float topy =  50;
    float rightx =  150;
    float bottomy =  150;
    // FILL
    canvas.drawRect(leftx, topy, rightx, bottomy, paint);

    paint.setStrokeWidth(10);
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.STROKE);
    // BORDER
    canvas.drawRect(leftx, topy, rightx, bottomy, paint);
}
Run Code Online (Sandbox Code Playgroud)

如果您想在单击时获取坐标,然后绘制矩形覆盖onTouchEvent方法并执行以下操作

class DrawView extends ImageView {

    float x, y;
    float width = 60.0f;
    float height = 50.0f;
    boolean touched = false;

    public DrawView(Context context) {
        super(context);
    }

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

    public DrawView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);


        if (touched) {
            Paint paint = new Paint();
            paint.setColor(Color.TRANSPARENT);
            paint.setStyle(Paint.Style.FILL);
            // FILL
            canvas.drawRect(x, y, (x + width) / 0.5f, (y + height) / 0.5f, paint);

            paint.setStrokeWidth(10);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE);
            // BORDER
            canvas.drawRect(x, y, (x + width) / 0.5f, (y + height) / 0.5f, paint);
        }
    }

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

}
Run Code Online (Sandbox Code Playgroud)