我正在尝试创建自定义视图,用于绘制从Url下载的图像。 代码是:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
dispatch_queue_t downloadImgQueue = dispatch_queue_create("imgDownload", NULL);
dispatch_async(downloadImgQueue, ^{
CGRect myViewSize = CGRectMake(0, 0, 100, 100);
NSURL *url = [NSURL URLWithString:@"http://www.mytripolog.com/wp-content/uploads/2011/05/large-big-size-world-political-map.jpg"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
dispatch_async(dispatch_get_main_queue(),^{
[image drawInRect:myViewSize];
});
});
dispatch_release(downloadImgQueue);
}
但这不起作用。我得到错误:
Dec 20 14:31:31 Mac.local AdSdk[1736] <Error>: CGContextSaveGState: invalid context 0x0
Dec 20 14:31:31 Mac.local AdSdk[1736] <Error>: CGContextSetBlendMode: invalid context 0x0
Dec 20 14:31:31 Mac.local AdSdk[1736] <Error>: CGContextSetAlpha: invalid context 0x0
Dec 20 14:31:31 Mac.local AdSdk[1736] <Error>: CGContextTranslateCTM: invalid context 0x0
Dec 20 14:31:31 Mac.local AdSdk[1736] <Error>: CGContextScaleCTM: invalid context 0x0
Dec 20 14:31:31 Mac.local AdSdk[1736] <Error>: CGContextDrawImage: invalid context 0x0
Dec 20 14:31:31 Mac.local AdSdk[1736] <Error>: CGContextRestoreGState: invalid context 0x0
我应该做些什么来改变它?
答案 0 :(得分:1)
drawRect:
应该只包含绘图代码。您应该将图像下载到其他位置并将其存储为视图的属性,然后在此方法中绘制它。或者,从外观上看,只需使用UIImageView
并设置图像?
drawRect:
。这可以是在动画期间,当其他元素出现或消失时,或任何其他情况。显然,您不希望每次发生这种情况时都进行下载。
答案 1 :(得分:0)
我有类似的问题,并使用UIGraphicsPushContext(context)/UIGraphicsPopContext(context)
围绕绘图代码解决了这个问题。上下文是用
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGImageAlphaPremultipliedLast);