canvas.drawRect不在图像上绘制矩形

时间:2016-06-17 06:48:24

标签: java android android-canvas

这里canvas.drawRect对不同的位图有不同的作用。我希望在顶部图像上绘制矩形,并希望矩形外部的图像部分变钝或模糊。请帮我。

draw.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Paint paint = new Paint();
            paint.setColor(Color.RED);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(2);

            Bitmap bitmap=((BitmapDrawable)image.getDrawable()).getBitmap();
            Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.RGB_565, true);

            Bitmap bitmap1 = Bitmap.createBitmap(600,400, Bitmap.Config.RGB_565);

            Rect r = new Rect();
            r.set(100,100,500,300);

            Canvas canvas = new Canvas(mutableBitmap);
            Canvas canvas1 = new Canvas(bitmap1);

            canvas.drawRect(r,paint);
            canvas1.drawRect(r,paint);

            image.setImageBitmap(mutableBitmap);
            image1.setImageBitmap(bitmap1);

        }
 });

enter image description here

2 个答案:

答案 0 :(得分:1)

如果要绘制矩形并使外部部分变钝,请以这种方式进行。创建一个位图并绘制全尺寸半透明矩形,然后用完全透明的颜色绘制另一个矩形。然后将Bitmap放在图像上。

试试这段代码:

            Bitmap bitmap = Bitmap.createBitmap(600,400,Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);

            RectF outerRectangle = new RectF(0, 0, 600, 400);
            RectF innerRectangle = new RectF(100, 100, 500, 300);

            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.BLACK);
            paint.setAlpha(80);
            canvas.drawRect(outerRectangle, paint);

            paint.setColor(Color.TRANSPARENT);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
            canvas.drawRect(innerRectangle, paint);

            paint.setColor(Color.RED);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(2);
            canvas.drawRect(innerRectangle, paint);

            image1.setImageBitmap(bitmap);

答案 1 :(得分:1)

你已经接受了Prasad给出的答案,但是这个答案没有解决帖子的标题,该帖子涉及处理一个Bitmap而不是另一个Bitmap的drawRect。我也有问题让矩形在图像上绘制,我找到的解决方案是将矩形添加到路径,然后使用drawPath。

Path boxPath = new Path();
boxPath.addRect(100, 100, 500, 300, Path.Direction.CW);
canvas.drawPath(boxPath, paint);