-1

In iOS,
I have a image.
Then, I want to make transparent area in specific path of the image.
The below image is some image. And, the heart area is random path to be transparent area.
I have just one full image.
I want to make transparent specific area of image. It is UIImage, not UIImageView. So, I can't use masking.

https://stackoverflow.com/a/8306254/2160799
I tried to use this solution, but the heart area was filled with blue color, not transparent. :(
The document explain like this. Because the solution uses imageContext(not window or bitmap contexts), I should not use the function(CGContext.clear(_:))

If the provided context is a window or bitmap context, Core Graphics clears the rectangle. For other context types, Core Graphics fills the rectangle in a device-dependent manner. However, you should not use this function in contexts other than window or bitmap contexts.

enter image description here

strawnut
  • 359
  • 5
  • 21

1 Answers1

2

You can use the below snippet. Here you would be creating an imagecontext using the api UIGraphicsBeginImageContextWithOptions(_:_:_:) and specified the opaque parameter as false which would make the end image transparent.

UIGraphicsBeginImageContextWithOptions(image.size, false, 0)
image.draw(at: .zero)
if let context = UIGraphicsGetCurrentContext() {
    context.addPath(bezierPath.cgPath)
    context.setBlendMode(.clear)
    context.setFillColor(UIColor.clear.cgColor)
    context.fillPath()

    let capturedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}
Subramanian Mariappan
  • 3,736
  • 1
  • 14
  • 29
  • I can't. In that case, the clear area was filled with blue color, I described. – strawnut Nov 13 '19 at 04:53
  • Have you tried creating a context with UIGraphicsBeginImageContextWithOptions api? – Subramanian Mariappan Nov 13 '19 at 04:55
  • Yes, I tried using UIGraphicsBeginImageContextWithOptions API. It is same result. :( – strawnut Nov 13 '19 at 04:57
  • Are you sure that you are not drawing anything else into the context? – Subramanian Mariappan Nov 13 '19 at 04:58
  • func clip(inPath path: CGPath) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, 0) defer { UIGraphicsEndImageContext() } draw(at: .zero) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.addPath(path) context.clip() context.clear(CGRect(x: 0, y: 0, width: size.width, height: size.height)) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil } return image } – strawnut Nov 13 '19 at 05:00
  • This is my code. It is extension function of UIImage – strawnut Nov 13 '19 at 05:00
  • @strawnut I've updated the snippet with blendmode. Can you try the same? – Subramanian Mariappan Nov 13 '19 at 05:06
  • Oh no... I am so sorry. The before codes are successful. I had tried to capture function: UIGraphicsImageRenderer. The problem is in here. Sorry you won – strawnut Nov 13 '19 at 05:14