Krishna Krishna - 3 months ago 29
Android Question

canvas.drawRect Not drawing rectangle on image

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

Answer

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);
Comments