I had a PNG image with a hole with transparent pixels inside, i tried so many things to change the "hole color". The solution i think is to make a colored mask with the shape of png image and put it behind the original image, but i have no ideia how to make this.
The lazy way to do this is changing the UIImageView background color, but the UIImageView background square will be there, and i get the same result changing the color of transparent area too. All i want is to change the transparent hole inside a PNG image using Swift
Urja's answer rewritten as a Swift extension for UIImage that accepts any UIColor as the background color:
extension UIImage {
func withBackground(color: UIColor) -> UIImage? {
var image: UIImage?
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(imageRect)
draw(in: imageRect, blendMode: .normal, alpha: 1.0)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
return nil
}
}
Well if it is a static image, why not just add the filling in Photoshop and use the modified image in your code? If not, you can put another view behind your image view with the filling color that you want as its background color, then use auto layout to set the relative size and position of the background view to the image view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With