2010-03-26 12 views
10

Me gustaría dibujar un CGImage en un CALayer, pero parece que solo quiero estirarlo.¿Cómo incrustar los contenidos de un CALayer?

El código de ejemplo:

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

me gustaría evitar la subclasificación si pudiera.

Respuesta

13

Puede crear un color con una imagen de patrón y establecerlo como el color de fondo de la capa.

Para hacer eso necesita envolver su CGImage en un CGPattern y hacer un CGColor desde él.

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

Este código se ha modificado a partir del código de muestra GeekGameBoard.

+1

acabo de notar + colorWithPatternImage en UIColor, es esta cosa ¿similar? –

+0

Sí, esto debería hacer lo mismo, aunque no lo he probado. 'UIColor' no siempre ha estado disponible en iPhone OS, así que estoy acostumbrado a usar los métodos' CGColor'. –

+1

No estoy del todo seguro, pero me parece que el uso de imágenes como 'backgroundColor' rompe la capacidad de animarlo. (He publicado una pregunta sobre eso [aquí] (http://stackoverflow.com/questions/5605618/core-animation-animation-doesnt-work).) – ryyst

0

Se puede emplear el método CGContextDrawTiledImage para este

2

Esto es bastante simple. Pero ten cuidado, esta es una API privada, úsala bajo tu propio riesgo.

de configuración de la siguiente manera

#import <QuartzCore/QuartzCore.h> 

CA_EXTERN NSString * const kCAContentsScalingRepeat; 

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

A continuación, sólo hacer esto

[myLayer setContentsScaling:kCAContentsScalingRepeat]; 
+0

Como mencionó @sdsykes, esta es una API privada y se debe usar con cuidado (si es que se usa). En caso de que se esté preguntando cuáles son los posibles valores, los únicos que pude encontrar fueron kCAContentsScalingStretch y kCAContentsScalingRepeat. Un poco de trivia :) – Buzzy

9

El código más sencilla de lograr esto es:

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

Tenga en cuenta que esto solo funciona en OS X 10.8 y superior –

+0

Ah, a la derecha. Estoy bastante centrado en iOS. Gracias por señalar eso. –

+0

¡Es un trabajo, pero todo está en reversa! –

Cuestiones relacionadas