C#图片圆角问题,怎么实现图片的四个角真正透明
展开全部
创建一个圆角GraphicsPath
进而创建一个Region
把Graphics的Clip属性设置为这个Region
然后DrawImageUnScaled画上去就行了
注意你画的那张图要把分辨率设置为和原来的图一样,因为DrawImage是按照测量大小绘制的。不把分辨率设为一样会出现留空白或者画不全。
关键代码如下,顺便描了一下边
(PathHelper.CreateRoundRectPath是一个自定义函数,用来创建圆角矩形路径的)
private Bitmap CreateRoundRectImage(Bitmap bmp,RoundStyle style, int Radius, bool Stroke, Color StrokeColor, int StrokeWidth)
{
Bitmap bp =new Bitmap(bmp.Width,bmp.Height );
bp.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
using (Graphics grfx = Graphics.FromImage(bp))
{
grfx.SmoothingMode = SmoothingMode.HighQuality;
Region rg1 = new Region(PathHelper.CreateRoundRectPath(new Rectangle(0, 0, bmp.Width, bmp.Height),
Radius, style, false));
grfx.Clip = rg1;
grfx.DrawImageUnscaled(bmp, 0, 0);
// 描边
if (Stroke)
{
grfx.ResetClip();
Region rg2 = new Region(PathHelper.CreateRoundRectPath(new Rectangle(StrokeWidth, StrokeWidth, bmp.Width - StrokeWidth * 2, bmp.Height - StrokeWidth * 2),
Radius, style, false));
rg1.Exclude(rg2);
grfx.FillRegion(new SolidBrush(StrokeColor), rg1);
}
}
return bp;
}
进而创建一个Region
把Graphics的Clip属性设置为这个Region
然后DrawImageUnScaled画上去就行了
注意你画的那张图要把分辨率设置为和原来的图一样,因为DrawImage是按照测量大小绘制的。不把分辨率设为一样会出现留空白或者画不全。
关键代码如下,顺便描了一下边
(PathHelper.CreateRoundRectPath是一个自定义函数,用来创建圆角矩形路径的)
private Bitmap CreateRoundRectImage(Bitmap bmp,RoundStyle style, int Radius, bool Stroke, Color StrokeColor, int StrokeWidth)
{
Bitmap bp =new Bitmap(bmp.Width,bmp.Height );
bp.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
using (Graphics grfx = Graphics.FromImage(bp))
{
grfx.SmoothingMode = SmoothingMode.HighQuality;
Region rg1 = new Region(PathHelper.CreateRoundRectPath(new Rectangle(0, 0, bmp.Width, bmp.Height),
Radius, style, false));
grfx.Clip = rg1;
grfx.DrawImageUnscaled(bmp, 0, 0);
// 描边
if (Stroke)
{
grfx.ResetClip();
Region rg2 = new Region(PathHelper.CreateRoundRectPath(new Rectangle(StrokeWidth, StrokeWidth, bmp.Width - StrokeWidth * 2, bmp.Height - StrokeWidth * 2),
Radius, style, false));
rg1.Exclude(rg2);
grfx.FillRegion(new SolidBrush(StrokeColor), rg1);
}
}
return bp;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询