I'm working with ImageSharp to do some basic image editing in my UWP app, and one of the things I need to do is to crop the image to a circle (you can assume the image is already a square).
I couldn't find a Clip
API that worked with anything else that rectangles, so I came up with the following snippet:
// Image is an Image<Argb32> instance
image.Mutate(context =>
{
context.Apply(target =>
{
double half = target.Height / 2.0;
unsafe
{
fixed (Argb32* p = target.GetPixelSpan())
for (int i = 0; i < target.Height; i++)
for (int j = 0; j < target.Width; j++)
if (Math.Sqrt((half - i).Square() + (half - j).Square()) > half)
p[i * target.Width + j] = default;
}
});
});
NOTE: that Square
method is just an extension that takes a double
and returns its squared value.
Now, this works fine, and it's reasonably fast as I'm working with small enough images (say, <= 250 pixels for each axis). This snippet simply sets each pixel that falls outside of the circle with radius height / 2
, centered at the center of the image, to a transparent pixel.
I wonder though if there wasn't another more intuitive method to do the same thing, that I just missed.
Thank you for your help!