Metal每日分享,调整透明度滤镜效果

2022-12-13  本文已影响0人  弹吉他的少年

本案例的目的是理解如何用Metal实现调整透明度效果滤镜,核心就是改变图像像素的透明度值;


Demo

实操代码

// 滤镜
let filter = C7Opacity.init(opacity: 0.75)

// 方案1:
ImageView.image = try? BoxxIO(element: originImage, filters: [filter, filter2, filter3]).output()

// 方案2:
ImageView.image = originImage.filtering(filter, filter2, filter3)

// 方案3:
ImageView.image = originImage ->> filter ->> filter2 ->> filter3

效果对比图

opacity: 0.25 opacity: 0.5 opacity: 0.75

实现原理

这款滤镜采用并行计算编码器设计.compute(kernel: "C7Opacity"),参数因子[opacity]

对外开放参数

/// 透明度调整,核心就是改变`alpha`
public struct C7Opacity: C7FilterProtocol {
    
    public static let range: ParameterRange<Float, Self> = .init(min: 0.0, max: 1.0, value: 1.0)
    
    /// Change the opacity of an image, from 0.0 to 1.0, with a default of 1.0
    @ZeroOneRange public var opacity: Float = range.value
    
    public var modifier: Modifier {
        return .compute(kernel: "C7Opacity")
    }
    
    public var factors: [Float] {
        return [opacity]
    }
    
    public init(opacity: Float = range.value) {
        self.opacity = opacity
    }
}

核心就是改变inColor.a

kernel void C7Opacity(texture2d<half, access::write> outputTexture [[texture(0)]],
                      texture2d<half, access::read> inputTexture [[texture(1)]],
                      device float *opacity [[buffer(0)]],
                      uint2 grid [[thread_position_in_grid]]) {
    const half4 inColor = inputTexture.read(grid);
    
    const half4 outColor = half4(inColor.rgb, half(*opacity) * inColor.a);
    
    outputTexture.write(outColor, grid);
}

Harbeth功能清单

最后

✌️.

上一篇 下一篇

猜你喜欢

热点阅读