1

私は、私たちの教授が私たちに、丸、四角、三角を確認するように言った宿題を持っています。

Shape.h:

#import <Foundation/Foundation.h>

@protocol Shape <NSObject>

@required
- (void)draw:(CGContextRef) context;
- (float)area;

@end

UIBotton描画するために別のクラスを呼び出すために使用します..

ビューコントローラーから描画関数を呼び出します

XYZController.m:

- (IBAction)rectButton:(id)sender {
    CGRect frame = [myView bounds];

    MyRect *rectView = [[MyRect alloc] initWithFrame:frame];

    [rectView draw: UIGraphicsGetCurrentContext()];
    [myView addSubview:rectView];
}

ドラッグしmyViewたのはどこですかUIView.xib

MyRectクラスで抽選を行います

MyRect.h:

@interface MyRect : UIView <Shape>

スーパークラスを NSObject から UIView に変更しました...正しく実行したかどうかわかりません..

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

しかし、その後、エラーが発生しました:

[...] <Error>: CGContextSetFillColorWithColor: invalid context 0x0
[...] <Error>: CGContextAddRect: invalid context 0x0
[...] <Error>: CGContextFillRects: invalid context 0x0

からだと思います[rectView draw: UIGraphicsGetCurrentContext()];

これを修正する方法はありますか?

ありがとう!

4

2 に答える 2

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 に答える