1

Here canvas.drawRect is working differently with different bitmap. I want the rectangle to be drawn on top image and want the part of image outside rectangle to be dull or blur. Please help me.

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

Krishna
  • 601
  • 2
  • 9
  • 32

2 Answers2

2

You have accepted the answer given by Prasad, but that answer did not address the title of the post, which deals with drawRect working on one Bitmap but not another. I also had problems getting rectangles to draw on top of an image and the solution I found was to add the rectangles to a Path and then use drawPath instead.

Path boxPath = new Path();
boxPath.addRect(100, 100, 500, 300, Path.Direction.CW);
canvas.drawPath(boxPath, paint);
tulipanh
  • 21
  • 2
1

If you want to draw a rectangle and make the outer portion dull, do it in this way. Create a bitmap and draw full size semitransparent rectangle and then draw another rectangle inside with full transparent colour. Then place that Bitmap on your image.

Try this code:

            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);
Venkata
  • 135
  • 8