在 UIImage 中裁剪一个透明孔

Cropping a transparent hole in an UIImage

我想在 UIImage 中创建一个孔,但它必须是透明孔。这个整体会放在精灵的中间,但为了测试,我在左上角创建了一个整体:

我通过以下方式完成了这项工作:

    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()

我不完全理解如何使用 UIGraphicsGetCurrentContext class。我不明白上下文是什么?或者为什么我必须同时使用 addRect() 和 fillRect()?或者是什么剪辑?

然而,尽管这些问题很重要,但我主要担心的是我创建的孔不透明:它是白色的。我尝试通过这样做来修复它:

 context.setFillColor(UIColor.clear.cgColor)

然而,这并没有造成任何漏洞。你们推荐我做什么?

试试 context.clear(CGRect)

如文档中所定义

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

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

这就是您的代码应有的样子

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

image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

希望对您有所帮助