本案例的目的是理解如何用Metal实现灰度系数效果滤镜,输入像素rgb进行次方运算获取到新的rgb;
// 灰度系数滤镜
let filter = C7Gamma.init(gamma: 3.0)
// 方案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
gamma: 1.0 | gamma: 2.0 | gamma: 3.0 |
---|---|---|
这款滤镜采用并行计算编码器设计.compute(kernel: "C7Gamma")
,参数因子[gamma]
;
对外开放参数
gamma
: 调整后的伽马,从0到3.0,默认值为1.0;/// 灰度系数
public struct C7Gamma: C7FilterProtocol {
public static let range: ParameterRange = .init(min: 0.0, max: 3.0, value: 1.0)
/// The adjusted gamma, from 0 to 3.0, with a default of 1.0
public var gamma: Float = range.value
public var modifier: Modifier {
return .compute(kernel: "C7Gamma")
}
public var factors: [Float] {
return [gamma]
}
public init(gamma: Float = range.value) {
self.gamma = gamma
}
}
对输入像素rgb进行次方运算pow(inColor.rgb, half3(*gamma))
,获取到新的rgb值;
kernel void C7Gamma(texture2d outputTexture [[texture(0)]],
texture2d inputTexture [[texture(1)]],
constant float *gamma [[buffer(0)]],
uint2 grid [[thread_position_in_grid]]) {
const half4 inColor = inputTexture.read(grid);
const half4 outColor = half4(pow(inColor.rgb, half3(*gamma)), inColor.a);
outputTexture.write(outColor, grid);
}
100+
种滤镜,同时也支持CoreImage混合使用。✌️.