Chen Li Yong Chen Li Yong - 1 year ago 67
iOS Question

How to make CGContextDrawPath draw on a nested subview?

I'm new to

concept in Apple iOS programming. Currently, I'm thinking in
. 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
where I want the drawing function to draw. But in there, I got confused with
. What "current context" is that? Is it the
? How if I want to set the "current context" to a view inside a
, so that all the pixel drawn will be relative to the view? Can I do that?

Answer Source

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);

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