2010-03-26 27 views
10

我想平鋪一個CALayer上的CGImage,但它似乎只是想拉伸它。如何平鋪CALayer的內容?

的示例代碼:

self.background = [UIImage imageNamed: @"Background.png"]; 
[documentDisplay.layer setContents: self.background.CGImage]; 

我想避免,如果我能繼承。

回答

13

您可以使用圖案圖像創建顏色並將其設置爲圖層的背景顏色。

要做到這一點,你需要換你的CGPatternCGImage並從中做出CGColor

// 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); 
} 

//assume image is the CGImage you want to assign as the layer background 
int width = CGImageGetWidth(image); 
int height = CGImageGetHeight(image); 
static const CGPatternCallbacks callbacks = {0, &drawPatternImage, &releasePatternImage}; 
CGPatternRef pattern = CGPatternCreate (image, 
         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); 
yourLayer.backgroundColor = color; //set your layer's background to the image 
CGColorRelease(color); 

此代碼是從GeekGameBoard示例代碼進行修改。

+1

我只注意到+ colorWithPatternImage中的UIColor,這個東西類似? – 2010-03-26 21:05:28

+0

是的,這應該做同樣的事情,雖然我還沒有測試過。 'UIColor'並不總是在iPhone OS中可用,所以我習慣於使用'CGColor'方法。 – 2010-03-27 00:07:28

+1

我不完全確定,但在我看來,使用圖像作爲'backgroundColor'打破了動畫的能力。 (我發佈了一個關於[這裏]的問題(http://stackoverflow.com/questions/5605618/core-animation-animation-doesnt-work)。) – ryyst 2011-04-09 18:54:13

0

您可以爲此使用CGContextDrawTiledImage方法

2

這很簡單。但要小心,這是一個私人API,使用時風險自負。

設置如下

#import <QuartzCore/QuartzCore.h> 

CA_EXTERN NSString * const kCAContentsScalingRepeat; 

@interface CALayer (CALayerAdditions) 
@property(copy) NSString *contentsScaling; 
@end 

然後只是這樣做

[myLayer setContentsScaling:kCAContentsScalingRepeat]; 
+0

正如@sdsykes所提到的,這是一個私人API,必須謹慎使用(如果有的話)。如果您想知道可能的值是什麼,我唯一能找到的就是kCAContentsScalingStretch和kCAContentsScalingRepeat。有點瑣事:) – Buzzy 2013-08-13 01:31:07

9

做到這一點,最簡單的代碼是:

CALayer *layer = [CALayer layer]; 
layer.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background_tile"]].CGColor; 
+0

注意這隻適用於OS X 10.8及以上版本 – 2013-05-21 00:01:55

+0

啊,對。我非常喜歡以iOS爲中心的。感謝您指出了這一點。 – 2013-05-21 18:53:53

+0

這是工作,但一切都是相反的! – 2014-06-18 05:23:33