Metal每日分享,纯色图片滤镜效果

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

本案例的目的是理解如何用Metal实现纯色图片效果滤镜,主要就是生成纯色图片;


Demo

实操代码

// 纯色滤镜
ImageView.image = C7Color.purple.mt.colorImage(with: CGSize(width: 600, height: 600))

效果对比图

purple white systemPink

实现原理

这款滤镜采用并行计算编码器设计.compute(kernel: "C7SolidColor")

对外开放参数

/// 纯色滤镜
public struct C7SolidColor: C7FilterProtocol, ComputeFiltering {
    
    public var color: C7Color = .white
    
    public var modifier: Modifier {
        return .compute(kernel: "C7SolidColor")
    }
    
    public func setupSpecialFactors(for encoder: MTLCommandEncoder, index: Int) {
        guard let computeEncoder = encoder as? MTLComputeCommandEncoder else { return }
        var factor = Vector4.init(color: color).to_factor()
        computeEncoder.setBytes(&factor, length: Vector4.size, index: index + 1)
    }
    
    public init(color: C7Color = .white) {
        self.color = color
    }
}

macOS获取RGBA值出错解决方案:

/// Fixed `*** -getRed:green:blue:alpha: not valid for the NSColor Generic Gray Gamma 2.2 Profile colorspace 1 1;
/// Need to first convert colorspace.
/// See: https://stackoverflow.com/questions/67314642/color-not-valid-for-the-nscolor-generic-gray-gamma-when-creating-sktexture-fro
/// - Returns: Color.
func usingColorSpace_sRGB() -> C7Color {
    #if os(macOS)
    let colors: [C7Color] = [
        .white, .black, .gray, .systemPink
    ]
    if colors.contains(base) {
        return base.usingColorSpace(.sRGB) ?? base
    }
    #endif
    return base
}

取出RGBA像素即可;

kernel void C7SolidColor(texture2d<half, access::write> outputTexture [[texture(0)]],
                         texture2d<half, access::read> inputTexture [[texture(1)]],
                         device float4 *colorVector [[buffer(0)]],
                         uint2 grid [[thread_position_in_grid]]) {
    const half4 color = half4(*colorVector);
    
    const half4 outColor = half4(color[0], color[1], color[2], color[3]);
    
    outputTexture.write(outColor, grid);
}

根据指定颜色和尺寸生成纯色图片;

#if HARBETH_COMPUTE // Compute module
extension Queen where Base: C7Color {
    
    /// Create a solid color image.
    /// - Parameters:
    ///   - color: Indicates the color.
    ///   - size: Indicates the size of the solid color diagram.
    /// - Returns: Solid color graph.
    public func colorImage(with size: CGSize = CGSize(width: 1, height: 1)) -> C7Image? {
        let width  = Int(size.width > 0 ? size.width : 1)
        let height = Int(size.height > 0 ? size.height : 1)
        let texture = Processed.destTexture(width: width, height: height)
        let filter = C7SolidColor.init(color: base)
        let result = try? Processed.IO(inTexture: texture, outTexture: texture, filter: filter)
        return result?.toImage()
    }
}
#endif

Harbeth功能清单

最后

✌️.

上一篇下一篇

猜你喜欢

热点阅读