在ImageVIew上绘制矩形

Bha*_*vna 3 java android

我想实现裁剪功能,在该功能上我想在imageView上有一个小矩形。矩形应该是静态的,我想移动图像并在矩形区域内进行裁剪。然后将矩形内的图像作为裁剪后的图像。我尝试使用Bitmap作为参数创建画布,但没有用。我已经做了很多尝试来搜索如何执行此操作。但在任何地方都找不到。请帮忙..

Bitmap bitmap=BitmapFactory.decodeResource(this.getResources(), R.drawable.indoor);

    Bitmap mutBitmap = Bitmap.createBitmap(200, 400,bitmap.getConfig());

    Canvas canvas = new Canvas(mutBitmap);

            Paint paint = new Paint();
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.FILL_AND_STROKE);
            paint.setStrokeWidth(10);
            float leftx = 20;
            float topy = 20;
            float rightx = 50;
            float bottomy = 100;
            canvas.drawRect(leftx, topy, rightx, bottomy, paint);
Run Code Online (Sandbox Code Playgroud)

我正在使用上面的代码,但是imageView上没有绘制矩形。

Amu*_*are 5

您需要将绘图代码放入onDraw()视图的方法中才能显示。您应该创建一个从imageView继承的自定义类,然后重写如下onDraw()方法:

class DrawView extends ImageView {

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

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

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

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

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(10);
        float leftx = 20;
        float topy = 20;
        float rightx = 50;
        float bottomy = 100;
        canvas.drawRect(leftx, topy, rightx, bottomy, paint);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的布局中,包含DrawView而不是当前ImageView