首先在 iOS 开发工具中,“设置图片的填充色”通常指的是对图片(如模板图标)设置颜色填充 找到Assets.xcassets -> 点击相应图片 -> 点击右侧菜单栏 -> "Show the Attributes inspector"选项 -> Render As -> 选择 “Template Image”
方法一:使用 UIImage 的 withRenderingMode(.alwaysTemplate) + tintColor 适用于 纯色图标类 PNG(如白底黑图、透明背景图) 步骤: 准备好一张透明背景的单色 PNG 图片(推荐使用黑色图标 PNG)。
导入图片到 Asset Catalog(建议勾选“Preserve Vector Data”,并设置为 Template Image)。
使用如下代码: let imageView = UIImageView(image: UIImage(named: "icon")?.withRenderingMode(.alwaysTemplate)) imageView.tintColor = UIColor.red // 替换成你想要的颜色 效果:将 PNG 图标变成指定颜色(如红色、主题色等)
方法二:使用 CoreGraphics 或 CoreImage 改变图片颜色(适合复杂图案 PNG) 步骤: func tintedImage(original: UIImage, color: UIColor) -> UIImage? { UIGraphicsBeginImageContextWithOptions(original.size, false, original.scale) guard let context = UIGraphicsGetCurrentContext(), let cgImage = original.cgImage else { return nil }
let rect = CGRect(origin: .zero, size: original.size)
// 画原图
context.translateBy(x: 0, y: original.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(.normal)
context.draw(cgImage, in: rect)
// 设置颜色并叠加
context.setBlendMode(.sourceIn)
context.setFillColor(color.cgColor)
context.fill(rect)
let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return coloredImage
} 使用方式: let newImage = tintedImage(original: UIImage(named: "your_png")!, color: UIColor.blue) imageView.image = newImage 适合处理多色图、复杂图案的色彩统一。
方法三:使用 CIColorControls 等滤镜调整色调(更自由控制) func adjustColor(image: UIImage, hue: CGFloat, saturation: CGFloat, brightness: CGFloat) -> UIImage? { guard let cgImage = image.cgImage else { return nil } let ciImage = CIImage(cgImage: cgImage)
let filter = CIFilter(name: "CIColorControls")!
filter.setValue(ciImage, forKey: kCIInputImageKey)
filter.setValue(saturation, forKey: kCIInputSaturationKey)
filter.setValue(brightness, forKey: kCIInputBrightnessKey)
let context = CIContext()
if let output = filter.outputImage,
let cgImgResult = context.createCGImage(output, from: output.extent) {
return UIImage(cgImage: cgImgResult)
}
return nil
} 用于特效处理或色彩微调场景