Chen Li Yong Chen Li Yong - 3 months ago 17
iOS Question

How to make CGContextDrawPath draw on a nested subview?

I'm new to

context
concept in Apple iOS programming. Currently, I'm thinking in
views
. I want to draw an arc using the easiest method possible, and then I found this question and answer. But then I'm confused with context concept. I thought to draw something, I will need to call the drawing function and supply the
view
where I want the drawing function to draw. But in there, I got confused with
UIGraphicsGetCurrentContext()
. What "current context" is that? Is it the
UIScreen.mainScreen()
? How if I want to set the "current context" to a view inside a
UICollectionViewCell
, so that all the pixel drawn will be relative to the view? Can I do that?

Answer

The way you draw in CocoaTouch is to subclass UIView to create a custom view and implement the drawRect:(CGRect)rect method. Put your drawing code inside drawRect. Something like:

-(void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();
   CGPathRef path = CGPathCreateWithRect(rect, NULL);
   [[UIColor blueColor] setStroke];
   CGContextSetLineWidth(context, 4.0);
   CGContextAddPath(context, path);
   CGContextDrawPath(context, kCGPathFillStroke);
   CGPathRelease(path);
 }

You can put your custom UIView inside of a UICollectionViewCell if you want.