Skip to content

Instantly share code, notes, and snippets.

@danieljfarrell
Created January 26, 2013 10:35
Show Gist options
  • Save danieljfarrell/4641601 to your computer and use it in GitHub Desktop.
Save danieljfarrell/4641601 to your computer and use it in GitHub Desktop.
Functions to convert an NSImage (*pattern image*) to a CGColorRef color, following the advice from http://stackoverflow.com/questions/2520978/how-to-tile-the-contents-of-a-calayer
/* http://stackoverflow.com/questions/2520978/how-to-tile-the-contents-of-a-calayer */
// callback for CreateImagePattern.
static void DrawPatternImage (void *info, CGContextRef ctx) {
CGImageRef image = (CGImageRef) info;
CGContextDrawImage(ctx,
CGRectMake(0,0, CGImageGetWidth(image),CGImageGetHeight(image)),
image);
}
// callback for CreateImagePattern.
static void ReleasePatternImage( void *info ) {
CGImageRelease((CGImageRef)info);
}
CGColorRef CreateCGColorWithPatternFromNSImage( NSImage *image ) {
/* User needs to release the color */
NSData *imageData = [image TIFFRepresentation];
CFDataRef cfImageData = CFBridgingRetain(imageData);
CGImageSourceRef source = CGImageSourceCreateWithData(cfImageData, NULL);
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(source, 0, NULL);
CFRelease(cfImageData);
CFRelease(source);
//assume image is the CGImage you want to assign as the layer background
CGFloat width = [image size].width;
CGFloat height = [image size].height;
static const CGPatternCallbacks callbacks = {0, &DrawPatternImage, &ReleasePatternImage};
CGPatternRef pattern = CGPatternCreate (cgImage,
CGRectMake (0, 0, width, height),
CGAffineTransformMake (1, 0, 0, 1, 0, 0),
width,
height,
kCGPatternTilingConstantSpacing,
true,
&callbacks);
CGColorSpaceRef space = CGColorSpaceCreatePattern(NULL);
CGFloat components[1] = {1.0};
CGColorRef color = CGColorCreateWithPattern(space, pattern, components);
CGColorSpaceRelease(space);
CGPatternRelease(pattern);
return color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment