Home > Articles > Mobile Application Development & Programming

iOS Developer's Cookbook: Sprite Kit Label Shadows

Let your Sprite Kit labels pop by automatically adding shadows. Shadow node children add contrast and visibility.
Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020