Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions ASAttributedLabelNode.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//
// ASAttributedLabelNode.h
//
// Created by Peter Easdown on 27/11/16.
// Inspired by Alex Studnicka
//

#import <SpriteKit/SpriteKit.h>

@interface ASAttributedLabelNode : SKSpriteNode

@property (nonatomic, retain) NSAttributedString *attributedText;

- (id) initWithSize:(CGSize)size;

@end
61 changes: 61 additions & 0 deletions ASAttributedLabelNode.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//
// ASAttributedLabelNode.h
//
// Created by Peter Easdown on 27/11/16.
// Inspired by Alex Studnicka
//

#import "ASAttributedLabelNode.h"

@implementation ASAttributedLabelNode

- (id) initWithSize:(CGSize)size {
self = [super initWithColor:[UIColor clearColor] size:size];

return self;
}

- (void) setAttributedText:(NSAttributedString *)attributedText {
_attributedText = attributedText;

[self draw];
}

- (void) draw {
NSAttributedString *attrStr = self.attributedText;

if (attrStr == nil) {
self.texture = nil;

return;
}

float scaleFactor = [UIScreen mainScreen].scale;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGImageAlphaInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
CGContextRef context = CGBitmapContextCreate(nil, self.size.width * scaleFactor, self.size.height * scaleFactor, 8, 0, colorSpace, bitmapInfo);

if (context == nil) {
return;
}

CGContextScaleCTM(context, scaleFactor, scaleFactor);
CGContextConcatCTM(context, CGAffineTransformMake(1, 0, 0, -1, 0, self.size.height));
UIGraphicsPushContext(context);

float strHeight = [attrStr boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
float yOffset = (self.size.height - strHeight) / 2.0;
CGRect rect = CGRectMake(0.0, yOffset, self.size.width, strHeight);
[attrStr drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin context:nil];

CGImageRef imageRef = CGBitmapContextCreateImage(context);

if (imageRef != nil) {
self.texture = [SKTexture textureWithCGImage:imageRef];
CGImageRelease(imageRef);
}

UIGraphicsPopContext();
}

@end