【问题标题】:Cropping a transparent hole in an UIImage在 UIImage 中裁剪透明孔
【发布时间】:2017-07-22 17:33:26
【问题描述】:

我想在 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 类。我不明白上下文是什么?或者为什么我必须同时添加 addRect() 和 fillRect()?或者剪辑是什么?

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

 context.setFillColor(UIColor.clear.cgColor)

但是,这并没有造成任何漏洞。你们建议我做什么?

【问题讨论】:

  • 您应该阅读Quartz 2D Programming Guide。虽然该文档中的代码是用 Objective-C 编写的,但所有的概念和 API 都是相同的。

标签: ios swift core-graphics


【解决方案1】:

试试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 来自我的回答,/* Clear `rect'(即将矩形内的区域设置为透明)。 */
  • 我的意思是 clip() 是做什么的,但我会阅读更多关于它的内容,因为我对 UIGraphics 几乎一无所知。
猜你喜欢
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2016-10-25
  • 2023-03-24
  • 2010-09-14
  • 2018-07-08
  • 2011-02-07
相关资源
最近更新 更多