This is probably a simple thing. I’m trying to draw my first shapes in my ViewDidLoad. However my context is always null, I get “con = 0x0”. I’m not sure if I’m using this properly. I’ve pasted my code below.
- (void)viewDidLoad
{
[super viewDidLoad];
// obtain the current graphics context
CGContextRef con = UIGraphicsGetCurrentContext();
// draw a black (by default) vertical line, the shaft of the arrow
CGContextMoveToPoint(con, 100, 100);
CGContextAddLineToPoint(con, 100, 19);
CGContextSetLineWidth(con, 20);
CGContextStrokePath(con);
// draw a red triangle, the point of the arrow
CGContextSetFillColorWithColor(con, [[UIColor redColor] CGColor]);
CGContextMoveToPoint(con, 80, 25);
CGContextAddLineToPoint(con, 100, 0);
CGContextAddLineToPoint(con, 120, 25);
CGContextFillPath(con);
// snip a triangle out of the shaft by drawing in Clear blend mode
CGContextMoveToPoint(con, 90, 101);
CGContextAddLineToPoint(con, 100, 90);
CGContextAddLineToPoint(con, 110, 101);
CGContextSetBlendMode(con, kCGBlendModeClear);
CGContextFillPath(con);
}
And when debugging, the value of “con” is:
con = (CGContext)0x0
The problem with your code is that you are trying to draw when you are not supposed to.
You can either move your drawing code to the
drawRect:method in your view, because the operating system prepares a context into which you can draw before callingdrawRect:or you can create your own context and draw into it, export it as an image and display it using an UIImageView.