如何在swift编程中设置UIimage中的背景颜色

Riz*_*ikh 9 uiimage ios swift

我使用drawInRect()方法绘制图像我的矩形大小为120*120,我的图像是100*100我如何在swift中为我的图像设置背景颜色

dim*_*iax 17

斯威夫特 5、4

如果您需要绘制图像的背景,出于优化和装饰的目的,您可以通过特定方式绘制图像:

UIImage(named: "someImage")?.withBackground(color: .white)


延期

extension UIImage {
  func withBackground(color: UIColor, opaque: Bool = true) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
        
    guard let ctx = UIGraphicsGetCurrentContext(), let image = cgImage else { return self }
    defer { UIGraphicsEndImageContext() }
        
    let rect = CGRect(origin: .zero, size: size)
    ctx.setFillColor(color.cgColor)
    ctx.fill(rect)
    ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
    ctx.draw(image, in: rect)
        
    return UIGraphicsGetImageFromCurrentImageContext() ?? self
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该被接受。接受的一种改变图像颜色而不是背景。但这段代码可以完成工作。谢谢 (3认同)

Egg*_*ead 9

您也可以使用此扩展程序:

extension UIImage {
func imageWithColor(tintColor: UIColor) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)

    let context = UIGraphicsGetCurrentContext()!
    context.translateBy(x: 0, y: self.size.height)
    context.scaleBy(x: 1.0, y: -1.0);
    context.setBlendMode(.normal)

    let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
    context.clip(to: rect, mask: self.cgImage!)
    tintColor.setFill()
    context.fill(rect)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return newImage
}
}
Run Code Online (Sandbox Code Playgroud)

然后

image.imageWithColor("#1A6BAE".UIColor)
Run Code Online (Sandbox Code Playgroud)


Dil*_*ili 7

更新了@ Egghead的Swift 3解决方案

extension UIImage {
   static func imageWithColor(tintColor: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        tintColor.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

UIImage.imageWithColor(tintColor: <Custom color>)
Run Code Online (Sandbox Code Playgroud)