你最好的办法就是使用这样的东西。使用贝塞尔路径可能非常复杂,尤其是当您要绘制多个单词时。尝试以正确的顺序和相同的 y 位置绘制线条将需要大量的自定义工作和令人头疼的事情。
下面将画出您设置的任何单词。
var charLayers = [CAShapeLayer]()
func drawText() {
for layer in self.charLayers {
layer.removeFromSuperlayer()
}
let font = [NSAttributedString.Key.font: UIFont(name: fontNameHEre, size: FontSizeHere)! ]
let attributedString = NSMutableAttributedString(string: "myStringHere", attributes: font)
let charPaths = self.characterPaths(attributedString: attributedString, position: CGPoint(x: 255, y: 632))
self.charLayers = charPaths.map { path -> CAShapeLayer in
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = lineWidth
shapeLayer.path = path
return shapeLayer
}
}
结果将是您定义的字符串。会为你画出来的。
只要在需要绘图的地方调用函数drawText()
-------- 编辑
抱歉忘记添加重要功能
见下文
func characterPaths(attributedString: NSAttributedString, position: CGPoint) -> [CGPath] {
let line = CTLineCreateWithAttributedString(attributedString)
guard let glyphRuns = CTLineGetGlyphRuns(line) as? [CTRun] else { return []}
var characterPaths = [CGPath]()
for glyphRun in glyphRuns {
guard let attributes = CTRunGetAttributes(glyphRun) as? [String:AnyObject] else { continue }
let font = attributes[kCTFontAttributeName as String] as! CTFont
for index in 0..<CTRunGetGlyphCount(glyphRun) {
let glyphRange = CFRangeMake(index, 1)
var glyph = CGGlyph()
CTRunGetGlyphs(glyphRun, glyphRange, &glyph)
var characterPosition = CGPoint()
CTRunGetPositions(glyphRun, glyphRange, &characterPosition)
characterPosition.x += position.x
characterPosition.y += position.y
if let glyphPath = CTFontCreatePathForGlyph(font, glyph, nil) {
var transform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: characterPosition.x, ty: characterPosition.y)
if let charPath = glyphPath.copy(using: &transform) {
characterPaths.append(charPath)
}
}
}
}
return characterPaths
}