本案例的目的是理解如何用Metal实现图像波动效果滤镜,还可类似涂鸦效果,主要就是对纹理坐标进行正余弦偏移处理;
// 波动效果
let filter = C7Fluctuate.init(extent: 50, amplitude: 0.003, fluctuate: 2.5)
// 方案1:
let dest = BoxxIO.init(element: originImage, filter: filter)
ImageView.image = try? dest.output()
dest.filters.forEach {
NSLog("%@", "\($0.parameterDescription)")
}
// 方案2:
ImageView.image = try? originImage.make(filter: filter)
// 方案3:
ImageView.image = originImage ->> filter
这款滤镜采用并行计算编码器设计.compute(kernel: "C7Fluctuate")
,参数因子[extent, amplitude, fluctuate]
对外开放参数
amplitude
: 控制振幅的大小,越大图像越夸张;extent
: 控制波动程度,越大越密集;fluctuate
: 波动幅度;/// 波动效果,还可类似涂鸦效果
public struct C7Fluctuate: C7FilterProtocol {
/// 控制振幅的大小,越大图像越夸张
/// Control the size of the amplitude, the larger the image, the more exaggerated the image.
public var amplitude: Float = 0.002
public var extent: Float = 50.0
public var fluctuate: Float = 0.5
public var modifier: Modifier {
return .compute(kernel: "C7Fluctuate")
}
public var factors: [Float] {
return [extent, amplitude, fluctuate]
}
public init(extent: Float = 50.0, amplitude: Float = 0.002, fluctuate: Float = 0.5) {
self.extent = extent
self.amplitude = amplitude
self.fluctuate = fluctuate
}
}
纹理坐标归一化处理,然后获取到偏移正余弦值作为xy,取出纹理像素颜色;
kernel void C7Fluctuate(texture2d outputTexture [[texture(0)]],
texture2d inputTexture [[texture(1)]],
device float *extent [[buffer(0)]],
device float *amplitude [[buffer(1)]],
device float *fluctuate [[buffer(2)]],
uint2 grid [[thread_position_in_grid]]) {
constexpr sampler quadSampler(mag_filter::linear, min_filter::linear);
const float2 textureCoordinate = float2(float(grid.x) / outputTexture.get_width(), float(grid.y) / outputTexture.get_height());
float2 offset = float2(0, 0);
offset.x = sin(grid.x * *extent + *fluctuate) * *amplitude;
offset.y = cos(grid.y * *extent + *fluctuate) * *amplitude;
const float2 tx = textureCoordinate + offset;//mix(textureCoordinate, textureCoordinate+offset, 0.01);
const half4 outColor = inputTexture.sample(quadSampler, tx);
outputTexture.write(outColor, grid);
}
extent: 50, amplitude: 0.004, fluctuate: 5.0 | extent: 40, amplitude: 0.003, fluctuate: 2.0 | extent: 60, amplitude: 0.025, fluctuate: 2.0 |
---|---|---|
更多效果自己去测试玩吧~
100+
种滤镜,同时也支持CoreImage混合使用。✌️.