Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to colorize transparent holes in UIImage

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

like image 982
user1779394 Avatar asked Nov 25 '25 16:11

user1779394


2 Answers

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
  }

}
like image 145
Paul King Avatar answered Nov 27 '25 06:11

Paul King


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.

like image 23
Ahmed Hamed Avatar answered Nov 27 '25 05:11

Ahmed Hamed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!