Home > Articles > Mobile Application Development & Programming

iOS Developer's Cookbook: Sprite Kit Label Shadows

  • Print
  • + Share This
  • 💬 Discuss
From the author of
Let your Sprite Kit labels pop by automatically adding shadows. Shadow node children add contrast and visibility.

Who Knows What Evil Design Aesthetics Lurk in the Heart of Devs?

SKLabelNode is a deeply weird class. It's not just weird because it belongs to Sprite Kit, with cross-platform compromises and spit-and-band-aid construction. No, it's weird because if you dive into any instance, you'll realize that it's a vastly different creature altogether from UILabel.

As far as I can tell, Sprite Kit labels consist of a placeholder parent and a single sprite node child. The text appears to be drawn into the sprite and then displayed with respect to the parent. This, of course, would be no more than a passing fact of evolutionary convergence, like the Malagasy tenrecs if it were not for my obsession about adding a subclass to support shadows.

I settled on the interface requirements even before I wrote a line of code. I wanted to inherit all of SKLabelNode's standard behaviors but add a shadow that would update in synchrony with its properties.

@interface ShadowLabelNode : SKLabelNode
@property (nonatomic) CGPoint offset;
@property (nonatomic) UIColor *shadowColor;
@property (nonatomic) CGFloat blurRadius;
@end

And with that, I was off for an unexpected adventure to achieve the label shadow you see in Figure 1.

Figure 1 This custom label shadow includes color, radius, and blur customization

Going Custom

In my initial estimations, I thought building this class would take somewhat under 5 minutes. That's until I remembered that SKNode descends from UIResponder and not from UIView. Nodes don't provide customizable layers, and you can't just set their shadow properties with a few lines.

When I got past that mental hurdle and oriented myself into Sprite Kit realities, I realized that I would probably want to add a child label to build the shadow and an effect node to create blur. Label nodes are dynamic things. At any time, they may change their font, size, alignment, and more. Because a shadow must always be current, I blocked out an updateShadow method I could call whenever any relevant property updated.

- (void) updateShadow
{
   // do something here
}

Standard key-value observing enables you to track updates that affect the shadow. These include changes in text, font, and alignment.

- (instancetype) initWithFontNamed:(NSString *)fontName
{
    if (!(self = [super initWithFontNamed:fontName])) return self;

    // Set defaults
    self.fontColor = [UIColor blackColor];
    _offset = CGPointMake(1, -1); // right and down in default scene
    _blurRadius = 3;
    _shadowColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.8];
    
    // Set observers
    for (NSString *keyPath in @[@"text", @"fontName", @"fontSize", @"verticalAlignmentMode", @"horizontalAlignmentMode", @"fontColor"])
        [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL];
    hasObservers = YES;
    
    // Initialize shadow
    [self updateShadow];
    
    return self;
}

When these properties update, the observer redirects to the updateShadow method.

- (void) observeValueForKeyPath:(NSString *)keyPath
                       ofObject:(id)object
                         change:(NSDictionary *)change
                        context:(void *)context
{
    [self updateShadow];
}

In addition, this custom class calls updateShadow whenever shadow properties update, specifically offset, blurRadius, and shadowColor. Custom setters provide this update in their implementation.

- (void) setOffset:(CGPoint)offset
{
    _offset = offset;
    [self updateShadow];
}

- (void) setBlurRadius:(CGFloat)blurRadius
{
    _blurRadius = blurRadius;
    [self updateShadow];
}

- (void) setShadowColor:(UIColor *)shadowColor
{
    _shadowColor = shadowColor;
    [self updateShadow];
}

Ordering Children

Knowing the shadow label needed to sit behind its parent and implementing that fact took many, many iterations. Several of these were successful but extremely ugly. At some point I had to stop thinking like a UIKit developer and shift my focus towards SpriteKit instead. iOS/JavaScript developer Jeremy Dowell forcefully reminded me about SKNode's zPosition property. The property places a node along a z-axis that projects toward and away from your user. Larger values are closer to the user; lower values are closer to the device. To render the shadow behind the label, the shadow's zPosition needed to adjust down:

[self insertChild:childNode atIndex:0];
childNode.zPosition = self.zPosition - 1;

I quickly learned that you cannot skip this step. Even if you've told the label to put the child at index 0, "behind" the super-secret internal sprite node, the label will casually ignore you. Figure 2 shows the results when you omit the zPosition line for this implementation.

Figure 2 You must update the shadow's zPosition to enable it to render behind its parent. The zPosition line was commented out for this screen shot

This difference in zPosition means you must also be very careful when animating shadowed items. As you see in Figure 3, objects may pass between a label and its shadow due to this zPosition difference.

Figure 3 As it moves, the star-shaped node passes between the "Hello" label and its shadow. Both the star and the "Hello" are at zPositions of 0. The shadow is at a zPosition of -1, so it renders behind the star and not on top of it

Creating an Effect Node

The SKEffectNode class enables you to blur your shadow. This class applies Core Image filters to its child nodes, providing a way to harness special effects within a Sprite Kit scene. Apple's documentation explains, "When effects are enabled, the effect node renders its children to an image, applies the filter to it, and then blends the filtered image into the parent’s framebuffer."

Building effects into your nodes is surprisingly easy. After you instantiate a filter, you may skip the input and output elements. For a blur, that means you just set the inputRadius. Assign the filter, and enable shouldEnableEffects. The magic takes place on any children you add to the effect node. Here is the final version of the updateShadow method, where you see the rest of the shadow label story.

NSString *const ShadowEffectNodeKey = @"ShadowEffectNodeKey";

- (void) updateShadow
{
    SKEffectNode *effectNode = (SKEffectNode *)[self childNodeWithName:ShadowEffectNodeKey];
    if (!effectNode)
    {
        effectNode = [SKEffectNode node];
        effectNode.name = ShadowEffectNodeKey;
        effectNode.shouldEnableEffects = YES;
        effectNode.zPosition = -1;
    }
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setDefaults];
    [filter setValue:@(_blurRadius) forKey:@"inputRadius"]; // blur radius may change
    effectNode.filter = filter;
    [effectNode removeAllChildren];
    
    // Duplicate and offset the label
    SKLabelNode *labelNode = [SKLabelNode labelNodeWithFontNamed:self.fontName];
    labelNode.text = self.text;
    labelNode.fontSize = self.fontSize;
    labelNode.verticalAlignmentMode = self.verticalAlignmentMode;
    labelNode.horizontalAlignmentMode = self.horizontalAlignmentMode;
    labelNode.fontColor = _shadowColor; // shadow not parent color
    labelNode.position = _offset; // offset from parent
    [effectNode addChild:labelNode];
    
    [self insertChild:effectNode atIndex:0];
}

Each time the parent label updates, this method builds a new child. The child mimics the parent's properties except for the color (set by the shadowColor property) and is offset via the offset property. The effect node blurs it to the current blurRadius property setting.

Creating More General Shadows

Shadows aren't just for labels. If you're pretty sure the node is not going to change very much (and, importantly, not rotate), use the following approach for any SKNode or subclass. The following code copies a node's texture with textureFromNode:. This renders a node tree into a flat texture, which you can color blend and multiply to establish a shadow.

- (SKTexture *) nodeTexture
{
    return [self.scene.view textureFromNode:self];
}

- (void) setShadowAtOffset: (CGPoint) offset radius: (CGFloat) blurRadius color: (UIColor *) shadowColor
{
    // Remove any existing shadow
    SKNode *child = [self childNodeWithName:NodeShadowKey];
    [child removeFromParent];

    // Build the blur node
    SKEffectNode *blurNode = [SKEffectNode node];
    blurNode.shouldEnableEffects = YES;
    blurNode.position = offset;
    blurNode.shouldCenterFilter = YES;
    blurNode.zPosition = self.zPosition - 1;
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setDefaults];
    [filter setValue:@(blurRadius) forKey:@"inputRadius"];
    blurNode.filter = filter;

    // Copy and blend the node
    SKSpriteNode *xerox = [SKSpriteNode spriteNodeWithTexture:self.nodeTexture];
    xerox.color = shadowColor;
    xerox.colorBlendFactor = 1.0;
    xerox.zPosition = self.zPosition - 1;
    xerox.blendMode = SKBlendModeMultiply;
    xerox.position = offset;
    xerox.name = @"CopiedNode";
    xerox.size = self.frame.size;
   
    // Attach the copy to the blur node and the blur node to the original node
    [blurNode addChild:xerox];
    [self addChild:blurNode];
    blurNode.name = NodeShadowKey;
}

Wrap-Up

This write-up describes just one of many possible approaches you might take to build shadows for Sprite Kit labels. I know because I must have built at least a dozen versions before I settled on the one you read about here. If you'd like to kick the tires on this version and give it a whirl, download the source code from my Github repository.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus