在UIImage中裁剪一个透明的孔

时间:2022-12-03 00:03:08

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:

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

在UIImage中裁剪一个透明的孔

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?

我不完全理解如何使用UIGraphicsGetCurrentContext类。我不明白背景是什么?或者为什么我必须同时使用addRect()和fillRect()?或夹是什么吗?

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 个解决方案

#1


1  

Try with context.clear(CGRect)

尝试与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

希望这能帮助你

#1


1  

Try with context.clear(CGRect)

尝试与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

希望这能帮助你