How to add background colour in existing image using Swift?

Multi tool use
How to add background colour in existing image using Swift?
I am trying to add background colour to existing image but it is not working.
Here below is my code:-
extension UIImage {
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()
//self.type(of: init)(ciImage: CIImage(image: image)!)
return image
}
}
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)!)
}
}.
I am very new in Graphics and don't know how I can put background colour to an image.
In this white colour image is there and orange colour is background colour.
1 Answer
1
You should create a new image with background color and existing image.
try this.
func getImage(image: UIImage, backgroundColor: UIColor)->UIImage?{
UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
backgroundColor.setFill()
//UIRectFill(CGRect(origin: .zero, size: image.size))
let rect = CGRect(origin: .zero, size: image.size)
let path = UIBezierPath(arcCenter: CGPoint(x:rect.midX, y:rect.midY), radius: rect.midX, startAngle: 0, endAngle: 6.28319, clockwise: true)
path.fill()
image.draw(at: .zero)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
do you mean background color should not exceed white color bounds
– tailor
Jun 26 at 11:27
yes exactly the same.
– kishor0011
Jun 26 at 11:46
Please give me some idea so that I can do the same. Thanks
– kishor0011
Jun 26 at 12:27
okay check my edited answer
– tailor
Jun 26 at 12:42
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It is working as background colour But colour is coming out of box also. Just update my question please check.
– kishor0011
Jun 26 at 10:15