C# 给方形图片切圆角

发布时间:2024年01月01日

写在前面

在有些场景中,给图片加上圆角处理会让视觉效果更美观。

代码实现

    /// <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做了圆角处理,看上去效果比方方的好一些。

文章来源:https://blog.csdn.net/rjcql/article/details/135305242
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。