如何为ID2D1Bitmap或IWICBitmapSource实现圆角效果?
需求:为ID2D1Bitmap/IWICBitmapSource添加圆角效果
我有一张方形图片,需要给它加圆角效果。之前用System Bitmap结合GraphicsPath实现过这个效果,但换成ID2D1Bitmap或IWICBitmapSource时搞不定了。
相关效果说明:
- 效果示例:Picture example
- 当前效果:What i have
- 普通矩形效果:Spell normal rect
- 期望效果:What i need
- 圆角效果示例:Spell round corners
我搜了相关方案没找到准确结果,知道可以用蒙版或者特效实现,但不知道具体步骤。刚接触这部分技术,希望得到具体操作建议或代码。
以下是我用C#实现System Bitmap圆角的代码:
public static Image RoundCorners(string fileName, int cornerRadius) { var image = CreateImageFromGame(fileName); //获取位图 if (image is not null) { cornerRadius *= 2; Bitmap roundedImage = new(image.Width, image.Height); GraphicsPath gp = new(); 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); using (Graphics gr = Graphics.FromImage(roundedImage)) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.SetClip(gp); gr.DrawImage(image, 0, 0, image.Width, image.Height); } return roundedImage; } return null; }
基于Direct2D的实现思路与代码
在Direct2D中实现圆角图片,核心思路是用几何路径作为蒙版,将图片绘制到蒙版区域内,具体步骤和代码如下:
核心步骤
- 创建圆角矩形的
ID2D1PathGeometry作为裁剪蒙版 - 通过
PushLayer方法将图层绑定到蒙版路径 - 在图层内绘制目标
ID2D1Bitmap - 弹出图层完成绘制
C#(SharpDX)示例代码
假设已完成Direct2D设备、设备上下文初始化,且已加载好ID2D1Bitmap:
using SharpDX.Direct2D1; using SharpDX.Mathematics.Interop; // 设置圆角半径 float cornerRadius = 20f; // 图片的显示区域 RawRectangleF imageRect = new RawRectangleF(0, 0, bitmap.Size.Width, bitmap.Size.Height); // 1. 创建圆角矩形路径 var roundedRect = new RoundedRect(imageRect, cornerRadius, cornerRadius); using (var pathGeometry = new PathGeometry(direct2DFactory)) using (var geometrySink = pathGeometry.Open()) { geometrySink.AddRoundedRectangle(roundedRect); geometrySink.Close(); // 2. 配置图层参数,绑定几何蒙版 var layerParameters = new LayerParameters(); layerParameters.GeometricMask = pathGeometry; layerParameters.ContentBounds = imageRect; // 3. 推送图层并绘制图片 using (var layer = new Layer(direct2DDeviceContext)) { direct2DDeviceContext.PushLayer(layerParameters, layer); direct2DDeviceContext.DrawBitmap(bitmap, imageRect, 1f, BitmapInterpolationMode.HighQualityCubic); direct2DDeviceContext.PopLayer(); } }
补充说明
- 若使用
IWICBitmapSource,需先转换为ID2D1Bitmap才能绘制:
using SharpDX.WIC; // wicBitmapSource为已加载的IWICBitmapSource实例 var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)); var d2dBitmap = direct2DDeviceContext.CreateBitmapFromWicBitmap(wicBitmapSource, bitmapProperties);
- 建议将Direct2D设备上下文的
AntialiasMode设置为AntialiasMode.PerPrimitive,保证圆角边缘平滑。
内容的提问来源于stack exchange,提问作者Aloex
相关产品推荐
相关产品推荐

