我認爲最好的方法是獲取邊框。 基本思想是使用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 和更多詳情,請訪問也是這個page關於spritekit大綱文本。
謝謝@Alessandro Ornano,我會盡快檢查這種方法! –