写在前面
在有些场景中,给图片加上圆角处理会让视觉效果更美观。
代码实现
/// <summary>/// 将图片处理为圆角/// </summary>/// <param name="image"></param>/// <returns></returns>private Image DrawTransparentRoundCornerImage(Image image){Bitmap bm = new Bitmap(image.Width, image.Height);Graphics g = Graphics.FromImage(bm);g.FillRectangle(Brushes.Transparent, new Rectangle(0, 0, image.Width, image.Height));using (var path = CreateRoundedRectanglePath(new Rectangle(0, 0, image.Width, image.Height), image.Width / 2)){g.SetClip(path);}g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);g.Dispose();return bm;}/// <summary>/// 设置图片四个边角弧度/// </summary>/// <param name="rect"></param>/// <param name="cornerRadius"></param>/// <returns></returns>private GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int cornerRadius){var roundedRect = new GraphicsPath();roundedRect.AddArc(rect.X, rect.Y, cornerRadius * 2, cornerRadius * 2, 180, 90);roundedRect.AddLine(rect.X + cornerRadius, rect.Y, rect.Right - cornerRadius * 2, rect.Y);roundedRect.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y, cornerRadius * 2, cornerRadius * 2, 270, 90);roundedRect.AddLine(rect.Right, rect.Y + cornerRadius * 2, rect.Right, rect.Y + rect.Height - cornerRadius * 2);roundedRect.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y + rect.Height - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);roundedRect.AddLine(rect.Right - cornerRadius * 2, rect.Bottom, rect.X + cornerRadius * 2, rect.Bottom);roundedRect.AddArc(rect.X, rect.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);roundedRect.AddLine(rect.X, rect.Bottom - cornerRadius * 2, rect.X, rect.Y + cornerRadius * 2);roundedRect.CloseFigure();return roundedRect;}
调用示例
如图所示调用函数后给二维码中间插入的logo做了圆角处理,看上去效果比方方的好一些。