1

How can I extract the polygon path from a SKLabelNode? For example I want the edge path of a number like this to move along a SKSpriteNode:

enter image description here

Do you think is possible? Or I must create a polygon for each character like:

var pathNumberOne = CGPathCreateMutable()
CGPathMoveToPoint(pathNumberOne , nil, 0, 0)
CGPathAddLineToPoint(pathNumberOne , nil, 20, 0) 
CGPathAddLineToPoint.....
........
........
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
Simone Pistecchia
  • 2,746
  • 3
  • 18
  • 30

1 Answers1

0

I think the best way to do it's to obtain the borders. The basic idea is to use an SKShapeNode to draw the border and add it as a child of your SKLabelNode. Something like this:

if let path = createBorderPathForText() {
    let border = SKShapeNode()

    border.strokeColor = borderColor
    border.lineWidth = 7;
    border.path = path
    border.position = positionBorder(border)
    labelNode.addChild(border)
}

The difficult part is how to create a border for your text. This is where Core Text kicks in. With the function CTFontGetGlyphsForCharacters you retrieve the glyphs for all characters in your text string. For every glyph you can create the CGPath using CTFontCreatePathForGlyph. The only thing you have to do is add the CGPath of all characters together and use this in your SKShapeNode. You can do this using the function CGPathAddPath. To obtain the relative positions of the glyphs/characters you can use the function CTFontGetAdvancesForGlyphs. Putting it all together:

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
    }
}

You can find a nice project here on github called MKOutlinedLabelNode and for more details visit also this page about outline text in spritekit.

Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133