Possible to have anti-aliasing when drawing a clipped image?
If you want to go for full blown feathering you should consider taking a look at this article:
http://danbystrom.se/2008/08/24/soft-edged-images-in-gdi/
If you want a quick and easy solution you could probably draw the image first then draw a GraphicsPath on top of it using a solid white brush with antialiasing. You would do something like this:
Rectangle outerRect = ClientRectangle;
Rectangle rect = Rectangle.Inflate(outerRect, -20, -20);
using (Image img = new Bitmap("test.jpg"))
{
g.DrawImage(img, outerRect);
using (SolidBrush brush = new SolidBrush(Color.White))
using (GraphicsPath path = new GraphicsPath())
{
g.SmoothingMode = SmoothingMode.AntiAlias;
path.AddEllipse(rect);
path.AddRectangle(outerRect);
g.FillPath(brush, path);
}
}
The other answers here won't work if you want a transparent background because you cannot draw with a transparent brush - it doesn't do anything.
I found other answers that can do it (for example, using SetClip
), but it doesn't come out with an anti-aliased edge.
I found this answer that works, but that one is designed to just round the corners, not make it a circle. So I modified it.
Here's how you can crop an image to a circle with a transparent background and anti-aliased edges:
/// <summary>
/// Crop the given image into a circle (or ellipse, if the image isn't square)
/// </summary>
/// <param name="img">The image to modify</param>
/// <returns>The new, round image</returns>
private static Bitmap CropCircle(Image img) {
var roundedImage = new Bitmap(img.Width, img.Height, img.PixelFormat);
using (var g = Graphics.FromImage(roundedImage))
using (var gp = new GraphicsPath()) {
g.Clear(Color.Transparent);
g.SmoothingMode = SmoothingMode.AntiAlias;
Brush brush = new TextureBrush(img);
gp.AddEllipse(0, 0, img.Width, img.Height);
g.FillPath(brush, gp);
}
return roundedImage;
}
The other answers draw the background color on top of the image. Instead, this creates a new, transparent image first, then draws a cut-out of the image on top.