本案例的目的是理解如何用Metal實現純色圖片效果濾鏡,主要就是生成純色圖片;
Demo
實操代碼
// 純色濾鏡
ImageView.image = C7Color.purple.mt.colorImage(with: CGSize(width: 600, height: 600))
效果對比圖
- 不同參數下效果
purple | white | systemPink |
---|---|---|
實現原理
- 過濾器
這款濾鏡採用並行計算編碼器設計.compute(kernel: "C7SolidColor")
;
對外開放參數
-
color
: 生成的圖片顏色;
/// 純色濾鏡
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功能清單
- 支持ios系統和macOS系統
- 支持運算符函數式操作
- 支持多種模式數據源 UIImage, CIImage, CGImage, CMSampleBuffer, CVPixelBuffer.
- 支持快速設計濾鏡
- 支持合併多種濾鏡效果
- 支持輸出源的快速擴展
- 支持相機採集特效
- 支持視頻添加濾鏡特效
- 支持矩陣卷積
- 支持使用系統 MetalPerformanceShaders.
- 支持兼容 CoreImage.
- 濾鏡部分大致分爲以下幾個模塊:
最後
- 慢慢再補充其他相關濾鏡,喜歡就給我點個星🌟吧。
-
濾鏡Demo地址,目前包含
100+
種濾鏡,同時也支持CoreImage混合使用。 - 再附上一個開發加速庫KJCategoriesDemo地址
- 再附上一個網絡基礎庫RxNetworksDemo地址
- 喜歡的老闆們可以點個星🌟,謝謝各位老闆!!!
✌️.