我认为最好的方法是获得边界。
基本思想是使用SKShapeNode 绘制边框并将其添加为SKLabelNode 的子级。像这样的:
if let path = createBorderPathForText() {
let border = SKShapeNode()
border.strokeColor = borderColor
border.lineWidth = 7;
border.path = path
border.position = positionBorder(border)
labelNode.addChild(border)
}
困难的部分是如何为您的文本创建边框。这就是Core Text 发挥作用的地方。使用函数CTFontGetGlyphsForCharacters,您可以检索文本字符串中所有字符的字形。对于每个字形,您可以使用CTFontCreatePathForGlyph 创建CGPath。您唯一需要做的就是将所有字符的CGPath 加在一起,然后在您的SKShapeNode 中使用它。您可以使用函数CGPathAddPath 执行此操作。要获取字形/字符的相对位置,您可以使用函数CTFontGetAdvancesForGlyphs。把它们放在一起:
private func createBorderPathForText() -> CGPathRef? {
let chars = getTextAsCharArray()
let borderFont = CTFontCreateWithName(self.fontName, self.fontSize, nil)
var glyphs = Array(count: chars.count, repeatedValue: 0)
let gotGlyphs = CTFontGetGlyphsForCharacters(borderFont, chars, &glyphs, chars.count)
if gotGlyphs {
var advances = Array(count: chars.count, repeatedValue: CGSize())
CTFontGetAdvancesForGlyphs(borderFont, CTFontOrientation.OrientationHorizontal, glyphs, &advances, chars.count);
let letters = CGPathCreateMutable()
var xPosition = 0 as CGFloat
for index in 0...(chars.count - 1) {
let letter = CTFontCreatePathForGlyph(borderFont, glyphs[index], nil)
var t = CGAffineTransformMakeTranslation(xPosition , 0)
CGPathAddPath(letters, &t, letter)
xPosition = xPosition + advances[index].width
}
return letters
} else {
return nil
}
}
你可以在 github 上找到一个不错的项目 here,名为 MKOutlinedLabelNode
有关 spritekit 中的大纲文本的更多详细信息,请访问 page。