2016-06-21 73 views
1

如何從SKLabelNode中提取多邊形路徑?例如,我想了許多這樣的邊緣路徑沿着SKSpriteNode移動:如何從SKLabelNode獲取CGPath?

enter image description here

你覺得有可能嗎?或者我必須爲每個字符創建一個多邊形,例如:

var pathNumberOne = CGPathCreateMutable() 
CGPathMoveToPoint(pathNumberOne , nil, 0, 0) 
CGPathAddLineToPoint(pathNumberOne , nil, 20, 0) 
CGPathAddLineToPoint..... 
........ 
........ 

回答

0

我認爲最好的方法是獲取邊框。 基本思想是使用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大綱文本。

+1

謝謝@Alessandro Ornano,我會盡快檢查這種方法! –