Note that there are some explanatory texts on larger screens.

plurals
  1. POObjective-C costum drawing with draw: (CGContextRef *)context
    text
    copied!<p>I have a home work which our professor told us to make circle, square, and triangle confirm to a protocol called </p> <p><code>Shape.h</code>:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @protocol Shape &lt;NSObject&gt; @required - (void)draw:(CGContextRef) context; - (float)area; @end </code></pre> <p>and use <code>UIBotton</code> to call different class to draw..</p> <p>I call the draw function from my view controller </p> <p><code>XYZController.m</code>:</p> <pre><code>- (IBAction)rectButton:(id)sender { CGRect frame = [myView bounds]; MyRect *rectView = [[MyRect alloc] initWithFrame:frame]; [rectView draw: UIGraphicsGetCurrentContext()]; [myView addSubview:rectView]; } </code></pre> <p>where <code>myView</code> is a <code>UIView</code> I dragged onto <code>.xib</code> </p> <p>and perform draw in <code>MyRect</code> class </p> <p><code>MyRect.h</code>:</p> <pre><code>@interface MyRect : UIView &lt;Shape&gt; </code></pre> <p>I changed the super class from NSObject to UIView... Not sure if I did it correctly..</p> <p><code>MyRect.m</code>:</p> <pre><code>- (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setNeedsDisplay]; } return self; } - (void)draw : (CGContextRef) context { CGRect bounds = [self bounds]; CGRect originRect = CGRectMake(25.0, 25.0, 50.0, 75.0); CGContextAddRect(context, originRect); CGContextStrokePath(context); [[UIColor greenColor] setFill]; CGContextFillRect(context, originRect); } </code></pre> <p>But then I got the error:</p> <pre><code>[...] &lt;Error&gt;: CGContextSetFillColorWithColor: invalid context 0x0 [...] &lt;Error&gt;: CGContextAddRect: invalid context 0x0 [...] &lt;Error&gt;: CGContextFillRects: invalid context 0x0 </code></pre> <p>I guess it's from <code>[rectView draw: UIGraphicsGetCurrentContext()];</code></p> <p>Any idea of how to fix this?</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload