Crop a shape from an Android bitmap

Sometimes you want to crop a bitmap, but it’s not an ordinary cropping, it’s a cropping to get rounded corners, cropping to get it as a circle, cropping to get it as a star, or cropping to get it as any shape.

In this post, we will crop a heart ❤️ from an Android bitmap.

1- At first get a bitmap to crop a shape from it.

Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.image);

The source image

2- Create an empty and mutable bitmap with the same height and width of the source.

Bitmap output = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);

3- Create a canvas with the mutable bitmap to draw into.

Canvas canvas = new Canvas(output);

4- Create a paint with any solid color, this color is for drawing a heart which you want to crop from the bitmap.

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(0XFF000000);

5- Draw a heart path at the center of the canvas.

canvas.drawPath(path, paint);

Note: You can get the heart path by several ways but this isn’t our topic here.

Now the canvas became as the next image.

In our case, the heart shape which you have drawn is called the destination image, it’s the shape which you want to crop from the bitmap.

6- The magic will be in the next line of code, set the transfer mode which defines how source pixels are composited or merged with the destination pixels.

paint.setXfermode(new PorterDuffXfermode(porterDuffMode));

But what is the PorterDuff.Mode which you have set here?

You want to Keep the image pixels (the source) that cover the heart pixels (the destination), discards the remaining image pixels (the source) and the heart pixels (the destination), see the next image.

So you have set PorterDuff.Mode.SRC_IN 👍

Click here for more info about PorterDuff modes.


7- Draw the source image on the canvas which has the destination image and use the paint with the SRC_IN transformation mode.

canvas.drawBitmap(src, 0, 0, paint);

and this is the result which you have waited for 🎉🎉🎉

You can find the full sample on Github.

Thanks! I hope I have inspired you in drawing and transformation images in Android. Also I will be thankful if you click on 💚 and share the post to let more people benefit from it.

If you are interested in more Android posts, follow me on Twitter or Check my GitHub projects.