Reputation: 401
I'm trying to create custom view that draws image downloaded from Url. The code is:
- (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);
}
But this doesn't work. I Get errors:
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
What should I change to make this work ?
Upvotes: 0
Views: 903
Reputation: 221
I had similar issue and solved it with UIGraphicsPushContext(context)/UIGraphicsPopContext(context)
around the drawing code. context was created with
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGImageAlphaPremultipliedLast);
Upvotes: 0
Reputation: 119242
drawRect:
should only contain drawing code. You should be downloading the image somewhere else and storing it as a property of your view, then drawing it within this method. Or, by the look of it, just use a UIImageView
and set the image?
drawRect:
is called whenever any part of the view needs drawing. This can be during animations, when other elements appear or disappear, or any number of other situations. Clearly you don't want to be performing a download every time this happens.
Upvotes: 1