You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:45:34