Search code examples
winapigraphicsdirect2d

Can I round the corners of ID2D1Bitmap or IWICBitmapSource?


I have a square picture with which I would like to round the edges. I did it with System Bitmap and GraphicsPath, but it's different here. Picture example

What i have

Spell normal rect

What i need

Spell round corners

Maybe I'm thinking wrong and it's as simple as possible. I tried Googling, but I didn't find anything accurate. I've seen different ways through mask and effect, but I'm not sure. Can someone suggest I will be very grateful, I have just started my journey.

The code I use to crop the corners of an image in c#.

public static Image RoundCorners(string fileName, int cornerRadius)
{
    var image = CreateImageFromGame(fileName); //Получаем растр

    if (image is not null)
    {
        cornerRadius *= 2;
        Bitmap roundedImage = new(image.Width, image.Height);
        GraphicsPath gp = new();
        gp.AddArc(0, 0, cornerRadius, cornerRadius, 180, 90);
        gp.AddArc(0 + roundedImage.Width - cornerRadius, 0, cornerRadius, cornerRadius, 270, 90);
        gp.AddArc(0 + roundedImage.Width - cornerRadius, 0 + roundedImage.Height - cornerRadius, cornerRadius, cornerRadius, 0, 90);
        gp.AddArc(0, 0 + roundedImage.Height - cornerRadius, cornerRadius, cornerRadius, 90, 90);
        using (Graphics gr = Graphics.FromImage(roundedImage))
        {
            gr.SmoothingMode = SmoothingMode.HighQuality;
            gr.SetClip(gp);
            gr.DrawImage(image, 0, 0, image.Width, image.Height);
        }

        return roundedImage;
    }

    return null;
}

Specific actions I should try or code


Solution

  • You could try to use the DrawRoundedRectangle and FillRoundedRectangle methods to outline and fill a rounded rectangle.

    You could try to use ID2D1Bitmap to Create a Bitmap Brush. And then you could use the Bitmap Brush to fill a rounded rectangle.

    You could refer to the Docs:

    How to Create a Bitmap Brush