Reputation: 16051
I have a UIView-based class called Icon. In there, I want to have code similar to this:
UIView *finalView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
finalView.backgroundColor = [UIColor redColor];
UIGraphicsBeginImageContext(finalView.bounds.size);
[finalView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
The problem is, i don't want to have to put it in drawRect because that's called when my app makes each Icon in another view. How can i put this sort of code somewhere else in my Icon class? I tried putting it in 1 place and it gave me:
CGContextSaveGState: invalid context 0x0
CGContextSetAlpha: invalid context 0x0
CGContextSaveGState: invalid context 0x0
CGContextSetFillColorWithColor: invalid context 0x0
CGContextAddRect: invalid context 0x0
CGContextDrawPath: invalid context 0x0
CGContextRestoreGState: invalid context 0x0
CGContextRestoreGState: invalid context 0x0
Upvotes: 7
Views: 3332
Reputation: 8245
Make sure that the dimensions of the image context are not invalid. If they are for example {0,0} then you will get a NULL response creating the context and all calls needing a valid bitmap context will tell you that 0x0 is not a valid context.
Upvotes: 2
Reputation: 16861
Keep doing all your drawing in -drawRect:
. When something changes and you want your view to be re-drawn, sent it a -setNeedsDisplay
or -setNeedsDisplayInRect:
message.
Upvotes: 5
Reputation: 3389
Maybe you are looking for UIGraphicsPushContext(context)? You can make your image context current to draw on it at any place where UIKit is available. Do not forget to UIGraphicsPopContext() after your drawing.
Upvotes: 1
Reputation: 4698
How about putting it in initWithFrame:? Would that work for you?
Upvotes: 0