Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

.net - How to create image with rounded corners in C#?

I'd like to create image (from another one) with rounded corners with GDI+. What's the best way to do this?

PS: it's not for web, so I cannot make use of client CSS

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This function seems to do what you want. It can also easily be modified to return a Bitmap if needed. You'll also need to clean up any images you no longer want, etc.. Adapted from: http://www.jigar.net/howdoi/viewhtmlcontent98.aspx

using System.Drawing;
using System.Drawing.Drawing2D;

public Image RoundCorners(Image StartImage, int CornerRadius, Color BackgroundColor)
{
    CornerRadius *= 2;
    Bitmap RoundedImage = new Bitmap(StartImage.Width, StartImage.Height);
    using(Graphics g = Graphics.FromImage(RoundedImage))
    {
      g.Clear(BackgroundColor);
      g.SmoothingMode = SmoothingMode.AntiAlias;
      Brush brush = new TextureBrush(StartImage);
      GraphicsPath gp = new GraphicsPath();
      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);
      g.FillPath(brush, gp);
      return RoundedImage;
    }
}

Image StartImage = Image.FromFile("YourImageFile.jpg");
Image RoundedImage = this.RoundCorners(StartImage, 25, Color.White);
//Use RoundedImage...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...