Skip to content

Instantly share code, notes, and snippets.

@rbsgn
Created March 19, 2011 16:57
Show Gist options
  • Save rbsgn/877611 to your computer and use it in GitHub Desktop.
Save rbsgn/877611 to your computer and use it in GitHub Desktop.
Debugging mode for CALayers: highlights borders and dumps sublayers as images
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface CALayer (YXDebug)
- (UIImage *)snapshot;
- (void)dumpSublayerImagesToFolder:(NSString *)folderPath;
- (void)highlightSublayerBorders;
@end
#import "CALayer-YXDebug.h"
@implementation CALayer (YXDebug)
- (UIImage *)snapshot {
CGSize size = self.bounds.size;
if (CGSizeEqualToSize(size, CGSizeZero)) {
return nil;
}
if (UIGraphicsBeginImageContextWithOptions != NULL) {
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
} else {
UIGraphicsBeginImageContext(size);
}
[self renderInContext:UIGraphicsGetCurrentContext()];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
NSAssert(image != nil, @"Image mustn't be nil");
UIGraphicsEndImageContext();
return [[image retain] autorelease];
}
- (void)collectSublayerImagesTo:(NSMutableDictionary *)dict prefix:(NSString *)prefix {
NSUInteger count = [dict count];
NSString * className = [[self class] description];
NSString * key = nil;
if (prefix) {
key = [NSString stringWithFormat:@"%d-%@-%@", count, prefix, className];
} else {
key = [NSString stringWithFormat:@"%d-%@", count, className];
}
UIImage * image = [self snapshot];
if (image == nil) {
return;
}
[dict setObject:image forKey:key];
NSString * newPrefix = nil;
if (prefix) {
newPrefix = [prefix stringByAppendingFormat:@"-%@", className];
} else {
newPrefix = className;
}
for (CALayer * layer in [self sublayers]) {
[layer collectSublayerImagesTo:dict prefix:newPrefix];
}
}
- (NSDictionary *)sublayerImages {
NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity:10];
[self collectSublayerImagesTo:dict prefix:nil];
return [NSDictionary dictionaryWithDictionary:dict];
}
- (void)dumpSublayerImagesToFolder:(NSString*)folderPath {
NSDictionary * sublayerImages = [self sublayerImages];
for (NSString * key in [sublayerImages allKeys]) {
UIImage * image = [sublayerImages objectForKey:key];
NSData * data = UIImagePNGRepresentation(image);
NSString * path = [NSString stringWithFormat:@"%@/%@.png", folderPath, key];
[data writeToFile:path atomically:YES];
}
}
- (void)highlightSublayerBorders {
self.borderColor = [[UIColor redColor] CGColor];
self.borderWidth = 1.0;
for (CALayer * layer in [self sublayers]) {
[layer highlightSublayerBorders];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment