Pablo
Pablo

Reputation: 1332

Cropping a transparent hole in an UIImage

I want to create a hole within an UIImage, but it must be a transparent hole. This whole will be placed right in the middle of a sprite, but for the sake of testing, I am creating a whole in the upper left corner:

enter image description here

I accomplished this by:

    let hole = CGRect(x: 0, y: 0, width: 512, height: 512)
    let context = UIGraphicsGetCurrentContext()!
    context.addRect(hole)
    context.clip(using: .evenOdd)
    context.setFillColor(UIColor.white.cgColor)
    context.fill(hole)

    image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

I don't fully understand how to use the UIGraphicsGetCurrentContext class. I don't understand what is the context? or why do I have to both addRect() and fillRect()? or what clip is?

However, although those questions are important, my main concern is that the hole I have created is not transparent: it is white. I tried fixing it by doing this:

 context.setFillColor(UIColor.clear.cgColor)

However, that just didn't create any hole whatsoever. What do you guys recommend I do?

Upvotes: 3

Views: 382

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

Try with context.clear(CGRect)

as is defined in documentation

/* Clear `rect' (that is, set the region within the rect to transparent). */

@available(iOS 2.0, *)
public func clear(_ rect: CGRect)

this is how your code should be

let hole = CGRect(x: 0, y: 0, width: 512, height: 512)
let context = UIGraphicsGetCurrentContext()!
context.clear(hole)

image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

Hope this helps you

Upvotes: 2

Related Questions