I have a home work which our professor told us to make circle, square, and triangle confirm to a protocol called
Shape.h
:
#import <Foundation/Foundation.h>
@protocol Shape <NSObject>
@required
- (void)draw:(CGContextRef) context;
- (float)area;
@end
and use UIBotton
to call different class to draw..
I call the draw function from my view controller
XYZController.m
:
- (IBAction)rectButton:(id)sender {
CGRect frame = [myView bounds];
MyRect *rectView = [[MyRect alloc] initWithFrame:frame];
[rectView draw: UIGraphicsGetCurrentContext()];
[myView addSubview:rectView];
}
where myView
is a UIView
I dragged onto .xib
and perform draw in MyRect
class
MyRect.h
:
@interface MyRect : UIView <Shape>
I changed the super class from NSObject to UIView... Not sure if I did it correctly..
MyRect.m
:
- (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);
}
But then I got the error:
[...] <Error>: CGContextSetFillColorWithColor: invalid context 0x0
[...] <Error>: CGContextAddRect: invalid context 0x0
[...] <Error>: CGContextFillRects: invalid context 0x0
I guess it's from [rectView draw: UIGraphicsGetCurrentContext()];
Any idea of how to fix this?
Thanks!