gpt4 book ai didi

objective-c - 将使用 colorWithPatternImage 创建的 NSColor 转换为 CGColor?

转载 作者:行者123 更新时间:2023-12-03 16:46:47 25 4
gpt4 key购买 nike

我已经多次尝试将使用 colorWithPatternImage 的图像创建的 NSColor 来回转换为 CGColor。它总是失败,我得到奇怪的坏结果。

我想知道转换是否适用于使用平铺图像生成的颜色,或者根本不可能。这就是我转换颜色的方法:

-(CGColorRef) CIColorToCGColor: (CIColor *) ciColor {
CGColorSpaceRef colorSpace = [ciColor colorSpace];
const CGFloat *components = [ciColor components];
CGColorRef cgColor = CGColorCreate (colorSpace, components);
CGColorSpaceRelease(colorSpace);
return cgColor;
}

...

CIColor *ciColor = [[CIColor alloc] initWithColor: [NSColor colorWithPatternImage:backgroundImage]];
CGColorRef cgColor = [self CIColorToCGColor: ciColor];
[ciColor release];

最佳答案

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

关于objective-c - 将使用 colorWithPatternImage 创建的 NSColor 转换为 CGColor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14892550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com