Cropping a transparent hole in an UIImage

Viewed 347

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?

1 Answers
Related