在Swift中实现UIImage颜色遮罩:将不透明像素统一设为指定颜色
实现UIImage颜色遮罩:将所有不透明像素统一设置为指定颜色
刚好我之前做过类似的需求,咱们可以借助Core Image的CIColorMatrix滤镜来实现这个效果——既能保留原图片的透明度通道,又能把所有非透明的像素替换成你指定的颜色。
这里是完善后的代码实现:
extension UIImage { func applyColorMask(color: UIColor, context: CIContext) -> UIImage { guard let cgImageInput = self.cgImage else { print("applyColorMask: \(self) has no cgImage attribute.") return self } // 将CGImage转为CIImage let inputImage = CIImage(cgImage: cgImageInput) // 获取目标颜色的RGB值(归一化到0-1范围) var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) // 构建颜色矩阵:保留原alpha,替换RGB为目标颜色 // 矩阵格式: [R红, G红, B红, A红, 红偏移, // R绿, G绿, B绿, A绿, 绿偏移, // R蓝, G蓝, B蓝, A蓝, 蓝偏移, // R透, G透, B透, A透, 透偏移] let colorMatrix = [ 0, 0, 0, 0, red, 0, 0, 0, 0, green, 0, 0, 0, 0, blue, 0, 0, 0, 1, 0 ] as [CGFloat] // 创建颜色矩阵滤镜 guard let colorMatrixFilter = CIFilter(name: "CIColorMatrix") else { print("applyColorMask: Failed to create CIColorMatrix filter.") return self } colorMatrixFilter.setValue(inputImage, forKey: kCIInputImageKey) colorMatrixFilter.setValue(CIVector(values: colorMatrix, count: 20), forKey: "inputRVector") // 获取处理后的CIImage,转为UIImage guard let outputCIImage = colorMatrixFilter.outputImage, let outputCGImage = context.createCGImage(outputCIImage, from: outputCIImage.extent) else { print("applyColorMask: Failed to process image.") return self } return UIImage(cgImage: outputCGImage, scale: self.scale, orientation: self.imageOrientation) } }
关键说明:
- 我们用
CIColorMatrix滤镜重置RGB通道:把原图片的RGB分量全部清零,然后添加目标颜色的RGB偏移值,这样所有非透明像素就会变成指定颜色。 - 透明度通道保持不变(矩阵里的
A透设为1,偏移为0),原图片的透明区域依然保持透明。 - 建议复用全局的
CIContext,避免重复创建影响性能。
使用示例:
// 初始化全局复用的CIContext let sharedCIContext = CIContext(options: [.useSoftwareRenderer: false]) // 给目标图片应用红色遮罩 if let originalImage = UIImage(named: "yourImage"), let maskedImage = originalImage.applyColorMask(color: .red, context: sharedCIContext) { // 在这里使用处理后的maskedImage }
内容的提问来源于stack exchange,提问作者herme5
相关产品推荐
相关产品推荐

