Reputation: 2378
I use below code in viewLoad (i don't want to draw in - (void)drawRect:(CGRect)rect
)for add rect on view but doesn't work.why?
CGRect rect=CGRectMake(10,10,150,140);
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(context, red);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 10, 10);
CGContextAddRect(context, rect);
CGContextStrokePath(context);
Upvotes: 3
Views: 3805
Reputation: 94834
UIGraphicsGetCurrentContext()
will return nil when there is no current context. A context is created for you before drawRect:
is called; if you want to create a context manually, use UIGraphicsBeginImageContext
or UIGraphicsBeginImageContextWithOptions
to start one, UIGraphicsGetImageFromCurrentImageContext()
to extract the UIImage, and UIGraphicsEndImageContext()
when you're done with it to release the context. See the documentation for details.
You could also, of course, create a CGBitmapContextRef and use CoreGraphics calls directly rather than UIKit calls. There are pros and cons to each approach, the major difference being the default transformation matrix.
Upvotes: 3
Reputation: 92384
You can only draw when you've got a drawing context. You can either create an image context anywhere you like to create an image, or you can draw inside drawRect:
to draw to your view. You are not supposed to draw to your view outside of drawRect:
.
It might look like you're getting a context, but in fact you don't as UIGraphicsGetCurrentContext()
returns nil
outside of drawRect:
(or to be more correct: it only returns a context inside drawRect:
or if you've created and pushed an image context yourself).
Upvotes: 6