How to set background color in UIimage in fast programming

I draw an image using the drawInRect() method, my rectangle is 120 * 120 in size and my image is 100 * 100, how can I set the background color for my image in quick

+6
source share
4 answers

You can also use this extension:

 extension UIImage { func imageWithColor(tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext() as CGContextRef CGContextTranslateCTM(context, 0, self.size.height) CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, kCGBlendModeNormal) let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect CGContextClipToMask(context, rect, self.CGImage) tintColor.setFill() CGContextFillRect(context, rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext() return newImage } } 

And then

 image.imageWithColor("#1A6BAE".UIColor) 
+6
source

Updated @Egghead solution for 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 } } 

Using:

 UIImage.imageWithColor(tintColor: <Custom color>) 
+4
source

It is probably best to use the backgroundColor property of your UIImageView. You can do it as follows:

 self.imageView.backgroundColor = UIColor.redColor() 

The following predefined colors are available:

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

If you want to programmatically create a UIImage with a given color, you can do it like this:

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

Where var 'image' is your color UIImage.

+3
source

Another way to get an image with a background color with the extension: (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) 
+3
source

Source: https://habr.com/ru/post/981923/


All Articles