「这是我参与2022首次更文挑战的第22天,活动详情查看:2022首次更文挑战」
本案例的目的是理解如何用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]
;
对外开放参数
opacity
: 将图像的不透明度从0.0更改为1.0,默认值为1.0;
/// 透明度调整,核心就是改变`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);
}
最后
- 慢慢再补充其他相关滤镜,喜欢就给我点个星🌟吧。
✌️.