È possibile creare un colore con un'immagine di motivo e impostarlo come colore di sfondo del livello.
Per fare ciò è necessario avvolgere il proprio CGImage
in un CGPattern
e creare un CGColor
da esso.
// 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);
Questo codice viene modificato dal codice di esempio GeekGameBoard.
fonte
2010-03-26 03:52:54
ho appena notato + colorWithPatternImage in UIColor, è questa cosa simile? –
Sì, questo dovrebbe fare la stessa cosa, anche se non l'ho provato. 'UIColor' non è sempre stato disponibile su iPhone OS, quindi sono abituato ad usare i metodi' CGColor'. –
Non ne sono del tutto sicuro, ma mi sembra che usare le immagini come 'backgroundColor' interrompa la capacità di animarlo. (Ho pubblicato una domanda al riguardo [qui] (http://stackoverflow.com/questions/5605618/core-animation-animation-doesnt-work).) – ryyst