如何在SkiSharp中高效为SKBitmap添加透明度(无需遍历像素)
高效为SKBitmap添加透明度(无需逐像素遍历)
替换指定颜色为透明(替代System.Drawing.Bitmap.MakeTransparent)
利用SkiaSharp的SKColorFilter和SKCanvas渲染能力,可实现无需手动遍历像素的高效颜色替换,底层依赖Skia的硬件加速优化,性能远优于逐像素循环。
public static SKBitmap MakeTransparent(SKBitmap sourceBitmap, SKColor transparentColor) { // 确保目标Bitmap带有Alpha通道(RGBA格式) var targetBitmap = new SKBitmap( sourceBitmap.Width, sourceBitmap.Height, SKColorType.Rgba8888, SKAlphaType.Premul ); using (var canvas = new SKCanvas(targetBitmap)) using (var paint = new SKPaint()) { // 创建颜色过滤器:将指定颜色替换为透明 var colorFilter = SKColorFilter.CreateBlendMode(transparentColor, SKBlendMode.Clear); paint.ColorFilter = colorFilter; // 绘制原图像并应用过滤器 canvas.DrawBitmap(sourceBitmap, 0, 0, paint); } return targetBitmap; }
为整个图像添加透明度(调整全局不透明度)
如果需要给整张图片统一添加透明度而非替换特定颜色,可使用颜色矩阵过滤器实现:
public static SKBitmap ApplyGlobalOpacity(SKBitmap sourceBitmap, float opacity) { // 限制不透明度在0-1之间 opacity = Math.Clamp(opacity, 0f, 1f); var targetBitmap = new SKBitmap( sourceBitmap.Width, sourceBitmap.Height, SKColorType.Rgba8888, SKAlphaType.Premul ); // 构建颜色矩阵:仅调整Alpha通道的权重 float[] opacityMatrix = { 1, 0, 0, 0, 0, // Red通道 0, 1, 0, 0, 0, // Green通道 0, 0, 1, 0, 0, // Blue通道 0, 0, 0, opacity, 0 // Alpha通道 }; using (var canvas = new SKCanvas(targetBitmap)) using (var paint = new SKPaint()) { paint.ColorFilter = SKColorFilter.CreateColorMatrix(opacityMatrix); canvas.DrawBitmap(sourceBitmap, 0, 0, paint); } return targetBitmap; }
关键优势
- 性能优化:SkiaSharp的渲染操作由底层优化的C++引擎处理,支持GPU加速,比手动逐像素循环快数倍
- 跨平台兼容:替代Windows专属的
System.Drawing.Bitmap.MakeTransparent,可在Android、iOS、macOS、Linux等平台使用 - 代码简洁:无需复杂的嵌套循环,通过Skia的内置API实现需求
内容的提问来源于stack exchange,提问作者Ercan
相关产品推荐
相关产品推荐

