简体   繁体   English

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

[英]how to set a background color in UIimage in swift programming

I draw an image using drawInRect() method.我使用drawInRect()方法绘制图像。

My rectangle is size of 120*120 and my image is 100 * 100.我的矩形大小为 120 * 120,我的图像为 100 * 100。

How i can set a background color to my image in swift?如何快速为我的图像设置背景颜色?

Swift 5, 4斯威夫特 5、4

If you need to draw the background of an image, for optimization and decorative purposes, you can draw the image in a specific way:如果您需要绘制图像的背景,出于优化和装饰的目的,您可以通过特定方式绘制图像:

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


Extension延期

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
  }
}

You can also use this extension:你也可以使用这个扩展:

    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
        }
    }

And then进而

image.imageWithColor("#1A6BAE".UIColor)

EDIT: 2019-11: Updated to Swift 5 by @Yuto编辑:2019-11:由@Yuto 更新到 Swift 5

Updated @Egghead's solution for Swift 3更新了@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
    }
}

Usage :用法 :

UIImage.imageWithColor(tintColor: <Custom color>)

It's probably best to use the backgroundColor property of your UIImageView.最好使用 UIImageView 的 backgroundColor 属性。 You can do this as follows -您可以按如下方式执行此操作 -

self.imageView.backgroundColor = UIColor.redColor()

The following preset colors exist:存在以下预设颜色:

blackColor
darkGrayColor
lightGrayColor
whiteColor
grayColor
redColor
greenColor
blueColor
cyanColor
yellowColor
magentaColor
orangeColor
purpleColor
brownColor
clearColor

If you instead want to programmatically create a UIImage with a given color, you can do this as follows:如果您想以编程方式创建具有给定颜色的 UIImage,您可以按如下方式执行此操作:

var rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Where the var 'image' is your colored UIImage. var 'image' 是你的彩色 UIImage。

An other way to obtain an image with a background color with an extension is: (Swift 3)获取带有扩展名的背景颜色图像的另一种方法是:(Swift 3)

extension UIImage {

    /**
        Returns an UIImage with a specified background color.
        - parameter color: The color of the background
     */
    convenience init(withBackground color: UIColor) {

        let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size);
        let context:CGContext = UIGraphicsGetCurrentContext()!;
        context.setFillColor(color.cgColor);
        context.fill(rect)

        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        self.init(ciImage: CIImage(image: image)!)

    }
}

And then:进而:

// change UIColor.white with your color
let image = UIImage(withBackground: UIColor.white)

Solution for swift 4 based on the already acepted answer:基于已经接受的答案的 swift 4 解决方案:

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

    let context = UIGraphicsGetCurrentContext() as! CGContext
    context.translateBy(x: 0, y: size.height)
    context.scaleBy(x: 1, y: -1)
    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() as! UIImage
    UIGraphicsEndImageContext()

    return newImage
}

Usage:用法:

image.imageWithColor("#1A6BAE".UIColor)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM