In the last post we discussed “How to Crop an Image using the WriteableBitmap class”. If you didn’t read it yet, first try to understand that before reading this post as we are going to use it in this post very frequently.
Today in this post we are going to learn how to crop an image in different shapes like rectangle, circle or any other different complex shapes programmatically.
First we will need the proper shape to crop the image. That could be any shape control or any complex path control. Once we have that shape or path ready, we can go further to process our image to give a simple or complex shape that we decided.
For this demo, let us take three controls. The first one is a Rectangle shape, the second one is an Ellipse shape and the third one is a complex Path control. Here is the XAML code of that for your reference:
Now once we have the image and the chosen shape ready, we can go to the code behind to process the image. First, we will need to create a WriteableBitmap instance from the image that we have. We already discussed more about it in the following posts:
Now crop the writeable bitmap instance in proper dimension using the method that we created in last post. Here you will get a well shaped cropped image in hand. Then create a new ImageBrush and set the cropped image as the ImageSource of that. Later set the Fill property of the shape control or path control to the image brush and you will get a new well shaped image which can be a complex one based on your provided shape.
Here is the C# code implementation:
Here is the VB.Net code implementation:
This will create the following shaped images for you based on your choice which you can save to your defined location for later use:
I hope that, this post will be definitely help you if you are going to crop an image based on various shapes. This will be as simple as it is if you are going to crop it for any other more complex shapes.
In case any trouble, drop a line with your queries and I will try to help you at the earliest. Happy coding.