GDI+ 怎样将图片绘制成圆形的图片

大概意思就是不生成新的图片,而是将图片转换为圆形图片。

这里写图片描写叙述

实现代码例如以下:

private Image CutEllipse(Image img, Rectangle rec, Size size)
{
    Bitmap bitmap = new Bitmap(size.Width, size.Height);
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        using (TextureBrush br = new TextureBrush(img,System.Drawing.Drawing2D.WrapMode.Clamp, rec))
        {
            br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.FillEllipse(br, new Rectangle(Point.Empty, size));
        }
    }
    return bitmap;
}

然后调用方法就可以。

Image image = this.pictureBox1.Image;
Image newImage = CutEllipse(image, new Rectangle(0, 0, 150, 150), new Size(150, 150));
this.pictureBox2.Image = newImage;

那么用WPF怎样实现?实现就更简单了,不须要写后台代码,直接利用XAML就可以。

<Grid>
        <Ellipse Height="150" Width="150">
            <Ellipse.Fill>
                <ImageBrush ImageSource="Image/1_guwei4037.jpg" ></ImageBrush>
            </Ellipse.Fill>
        </Ellipse>
</Grid>

————————————————————————————————————

群里的@陈应钦对如上的方法提出一个问题,就是如上的方法图形的下边缘和右側边缘是一条直线,并非平滑的曲线。细心观察确实如此。

原因是我画到了picturebox控件中,本身picturebox控件border就占长度,正好又画满控件。所以右边和下边都是直线了(空间不够了)。

所以解决方式有两个:能够直接绘制到不占空间的区域(比方窗口中指定的Rectangle)。或者将绘制图形的长和宽缩小一点。

原文地址:https://www.cnblogs.com/claireyuancy/p/7346981.html