Dow*_*oat 15 core-graphics cgimage cgimagemaskcreate ios swift
我实际上要做的是在视图中有一个文本标签"切割"一个文本形状的孔.我试过使用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()
Run Code Online (Sandbox Code Playgroud)
基本上我已经成功创建了一个代码来创建一个CGImage
(mask
变量),它是我想要应用于整个图像的蒙版.
替换为context.draw(mask, in: rect)
(以查看掩码)时标记的行正确显示.所述掩模节目(正确地)为:
然而,一旦我尝试应用这个面具(使用context.clip(to: rect, mask: mask)
)没有任何反应!实际结果:
期望的结果是:
但由于某种原因,掩码未正确应用.
这段代码似乎应该可以正常工作,因为我一遍又一遍地阅读文档.我还试图在一个单独的CGContext中创建掩码,但它不起作用.此外,当我尝试将CGImage(mask
)转换为CGColorSpaceCreateDeviceGray()
使用时.copy(colorSpace:)
,它返回nil
.我已经在这两天了,所以任何帮助都表示赞赏
如果您希望标签具有完全半透明的文本,您可以使用混合模式而不是蒙版。
public class KnockoutLabel: UILabel {
public override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
context.setBlendMode(.clear)
self.drawText(in: rect)
}
}
Run Code Online (Sandbox Code Playgroud)
确保设置为isOpaque
“false
虽然”;默认情况下,视图假定它是不透明的,因为您使用不透明的背景颜色。
归档时间: |
|
查看次数: |
550 次 |
最近记录: |