You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:55:11