1

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!

4

2 回答 2

1

UIGraphicsGetCurrentContext() 将返回 nil,但在 drawRect: 中除外。UIKit 会在 drawRect: 之前创建上下文。

您也可以创建自己的上下文进行绘制。

UIKit 示例:

UIGraphicsBeginImageContext() 
UIGraphicsGetImageFromCurrentImageContext() to get image context
UIGraphicsEndImageContext()

核心图形示例:

CGBitmapContextCreate()

文件:

UIKit 函数参考

CGBitmapContext 参考

于 2013-04-18T08:44:02.983 回答
0

您将首先覆盖-drawRect:MyRect 类中的方法。然后使用

[[UIColor greenColor] set] // or setStroke, 'cause your using stroke and not fill!
CGContextStrokeRect(UIGraphicsGetCurrentContext(), rect)

您应该-drawRect:在 UIView 子类中使用并制作所有绘图。您无法从所需的位置获取上下文。仅在命名方法中。

于 2013-04-18T08:57:43.807 回答