我按照this answer中列出的说明填写Core Graphics中带有图案的图层。当图层是CALayer子类时,绘图工作正常。但是,当图层是CATiledLayer子类时,我在运行时会收到EXC_BAD_ACCESS
错误。
static void drawPatternImage (void *info, CGContextRef ctx)
{
CGImageRef image = (CGImageRef) info;
CGContextDrawImage(ctx,
CGRectMake(0,0, CGImageGetWidth(image),CGImageGetHeight(image)),
image); // EXC_BAD_ACCESS here :(
}
static void releasePatternImage( void *info )
{
CGImageRelease((CGImageRef)info);
}
// pattern creation
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);
theLayer.backgroundColor = color;
CGColorRelease(color);
在CATiledLayer子类中绘制图案图像需要做什么?
答案 0 :(得分:6)
我在“drawLayer”方法中为CATiledLayer类使用“CGContextDrawTiledImage”:
在.h:
@interface StarView : UIView {
UIImage *imgTextureCarta;
}
in .m
- (id)initWithFrame:(CGRect)frame {
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:@"aTexture" ofType:@"png"];
imgTextureCarta = [UIImage imageWithContentsOfFile: imagePath];
[imgTextureCarta retain];
CGImageRef texureCarta;
texureCarta = (imgTextureCarta.CGImage);
}
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context{
CGImageRef texureCarta;
texureCarta = (imgTextureCarta.CGImage);
CGRect bounds = layer.bounds;
CGContextSetBlendMode (context, 0);
CGContextClipToRect(context, layer.bounds);
CGContextDrawTiledImage(context, CGRectMake(0,0, 128, 120), texureCarta);
}
- (void)dealloc {
[imgTextureCarta release];
[super dealloc];
}