几周前我需要这样做。我发现这个答案基本上解决了这个问题,
如何平铺 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;
}