如何为CALayer设置平铺的背景图像?

时间:2013-02-12 12:30:30

标签: objective-c cocoa

当我为IKBrowserView设置背景时,根据视图大小调整背景大小:有没有办法将其设置为平铺图像,重复但从不调整大小?

NSImage*    backgroundImage = [NSImage imageNamed:@"wood-bg2.jpg"];
CALayer*    aLayer = [CALayer layer];
//aLayer.contents = backgroundImage;

CIColor *ci = [[CIColor alloc] initWithColor:[NSColor colorWithPatternImage:backgroundImage]];
CGColorSpaceRef cs = [ci colorSpace];
const CGFloat *comps = [ci components];
CGColorRef cgColor = CGColorCreate(cs, comps);

aLayer.backgroundColor = cgColor;
[itemThumbnailImageBrowserView setBackgroundLayer:aLayer];

我已经尝试了注释掉的代码和当前的代码,但都没有用。 感谢

1 个答案:

答案 0 :(得分:4)

NSColor的方法:

+ (NSColor *)colorWithPatternImage:(NSImage *)image

所以你可以这样做:

NSImage*    backgroundImage = [NSImage imageNamed:@"wood-bg2.jpg"];
CALayer*    aLayer = [CALayer layer];
aLayer.backgroundColor = [[NSColor colorWithPatternImage:backgroundImage] CGColor]; // - (CGColor) CGColor; is only available in OS X 10.8 and later
[itemThumbnailImageBrowserView setBackgroundLayer:aLayer];

OS X 10.8及更低版本

的更新

NSColor转换为CGColor(未经测试):

CIColor *ci = [[CIColor alloc] initWithColor:[NSColor colorWithPatternImage:backgroundImage]];
CGColorSpaceRef cs = [ci colorSpace];
const CGFloat *comps = [ci components];
CGColorRef cgColor = CGColorCreate(cs, comps);