我想要做的基本上是让文本标签通过视图“切割”一个文本形状的空洞。我尝试使用 self.mask = uiLabel
,但它们无法正确定位文本,所以我正在通过 Core Graphics 来实现。
这里是不起作用的代码(在 draw(_ rect: CGRect)
中):
let context = (UIGraphicsGetCurrentContext())!
// Set mask background color
context.setFillColor(UIColor.black.cgColor)
context.fill(rect)
context.saveGState()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes = [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium),
NSForegroundColorAttributeName: UIColor.white
]
let string = NSString(string: "LOGIN")
// This wouldn't vertically align so we calculate the string size and create a new rect in which it is vertically aligned
let size = string.size(attributes: attributes)
let position = CGRect(
x: rect.origin.x,
y: rect.origin.y + (rect.size.height - size.height) / 2,
width: rect.size.width,
height: size.height
)
context.translateBy(x: 0, y: rect.size.height)
context.scaleBy(x: 1, y: -1)
string.draw(
in: position,
withAttributes: attributes
)
let mask = (context.makeImage())!
context.restoreGState()
// Redraw with created mask
context.clear(rect)
context.saveGState()
// !!!! Below line is the problem
context.clip(to: rect, mask: mask)
context.restoreGState()
本质上,我已成功创建了用于应用于整个图像的蒙版CGImage
(命名为mask
)的代码。
当将标记行替换为context.draw(mask, in: rect)
(以查看蒙版)时,正确显示。正确显示的蒙版如下:
但是,一旦尝试使用context.clip(to: rect, mask: mask)
应用此蒙版,则没有任何变化!实际结果:
期望结果是:
但由于某种原因,蒙版未被正确应用。
这段代码似乎应该工作,因为我反复阅读了文档。我还尝试在单独的CGContext中创建蒙版,但没有成功。当我尝试使用.copy(colorSpace:)
将CGImage(mask
)转换为CGColorSpaceCreateDeviceGray()
时,它返回了nil
。我已经在这个问题上花了两天时间,所以感谢任何帮助。
UILabel
子视图的UIControl
自定义子类。 - Nicolas MiarisetNeedsDisplay()
方法解决了问题。 - Nicolas Miari