在 UIImage 中打一个清晰的洞

punch a clear hole in a UIImage

我正在尝试在 uiimage 中创建一个透明孔这是我目前所发现的:

let hole = CGRect(x: 0, y: 0, width: 50, height: 50)
let context = UIGraphicsGetCurrentContext()!
context.clear(hole)
myImage.image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

但我在 : let context = UIGraphicsGetCurrentContext()!

得到了零

我知道我需要在某处定义当前上下文,但我不确定在哪里以及如何定义

您需要有可用于绘图的上下文。使用 UIGraphicsBeginImageContext 显式创建一个,绘制完成后,调用 UIGraphicsEndImageContext 进行清理。

这是你的代码,调用 UIGraphicsBeginImageContext,包装在扩展方法中:

extension UIImage {
    func imageWithHole(at rect: CGRect) -> UIImage? {
        UIGraphicsBeginImageContext(self.size)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        self.draw(at: CGPoint.zero)
        context.clear(rect)
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resultImage
    }
}

这样使用:

let sourceImage = UIImage(named: "sample.jpg")

let imageWithHole = sourceImage?.imageWithHole(at: CGRect(x: 50, y: 50, width: 50, height: 50))