如何使用Swift创建图像负片(反色效果)的UIImage
Swift实现UIImage反色(负片)效果的两种方法
方法一:用Core Image滤镜快速实现
Core Image自带CIColorInvert滤镜,能一键生成反色效果,代码简洁且性能有系统优化,适合大多数场景。
import UIKit import CoreImage extension UIImage { func inverted() -> UIImage? { guard let ciImage = CIImage(image: self) else { return nil } let invertFilter = CIFilter(name: "CIColorInvert") invertFilter?.setValue(ciImage, forKey: kCIInputImageKey) guard let outputCI = invertFilter?.outputImage else { return nil } let context = CIContext(options: [.useSoftwareRenderer: false]) guard let outputCG = context.createCGImage(outputCI, from: outputCI.extent) else { return nil } return UIImage(cgImage: outputCG) } }
使用示例
// 加载原图并生成反色图 if let original = UIImage(named: "your_image"), let invertedImg = original.inverted() { yourImageView.image = invertedImg }
方法二:Core Graphics手动操作像素(自定义场景)
如果需要精细控制(比如只反色特定颜色通道),可以直接遍历像素数据处理,灵活性更高。
import UIKit extension UIImage { func invertedPixelwise() -> UIImage? { guard let cgImg = self.cgImage else { return nil } let width = cgImg.width let height = cgImg.height let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width // 初始化像素数据数组 var pixelData = [UInt8](repeating: 0, count: width * height * bytesPerPixel) // 创建绘图上下文 guard let context = CGContext(data: &pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } // 绘制原图到上下文 context.draw(cgImg, in: CGRect(x: 0, y: 0, width: width, height: height)) // 遍历像素,反色RGB通道(保留Alpha不变) for index in 0..<pixelData.count { if index % 4 != 3 { // 跳过Alpha通道(第4位) pixelData[index] = 255 - pixelData[index] } } // 生成新图片 guard let newCGImg = context.makeImage() else { return nil } return UIImage(cgImage: newCGImg) } }
使用示例
if let original = UIImage(named: "your_image"), let invertedImg = original.invertedPixelwise() { yourImageView.image = invertedImg }
两种方法对比
- Core Image法:代码短、实现快,系统负责优化性能,适合通用反色需求。
- Core Graphics法:可自定义像素处理逻辑,比如只反色红色通道,适合特殊场景,但代码量稍多。
内容的提问来源于stack exchange,提问作者Prateek Raj
相关产品推荐
相关产品推荐

