在UIImage中裁剪一个透明孔

3
我想在UIImage中创建一个透明的洞,这个洞将被放置在精灵的正中央,但为了测试,我会在左上角创建一个洞:

enter image description here

我通过以下方式完成了这个任务:
    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类。我不明白什么是上下文?或者为什么我既要添加addRect()又要填充fillRect()?又或者clip是什么?
然而,尽管这些问题很重要,但我的主要问题是我创建的孔不是透明的:它是白色的。我尝试通过以下方式修复它:
 context.setFillColor(UIColor.clear.cgColor)

然而,这根本没有创造任何漏洞。你们有什么建议吗?


你应该阅读Quartz 2D编程指南。虽然该文档中的代码是Objective-C,但所有的概念和API都是相同的。 - rmaddy
1个回答

2
尝试使用文档中定义的 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()

希望这能帮到您。

你为什么要删除 context.clip(using: .evenOdd)? - Pablo
@Pablo 因为在你的问题中是不必要的,只有清晰明了我们才能完成工作。 - Reinier Melian
它是做什么的? - Pablo
从我的回答中,@Pablo /* 清除“rect”(即将矩形内的区域设置为透明)。*/ - Reinier Melian
我的意思是clip()函数是做什么的,但是我会多读一些关于UIGraphics的资料,因为我对它几乎一无所知。 - Pablo
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接