如何将UIView子类化,然后如何使用drawRect绘制图形?

时间:2011-08-01 20:10:07

标签: objective-c cocoa-touch

如何对UIView进行子类化,然后如何将其与drawRect一起使用来绘制图形? 我是否需要添加框架然后包含在头文件QuartzCore或其他任何内容中?


综合解决方案:


#import <UIKit/UIKit.h>
@interface drawingViewController : UIViewController {
}
@end

#import "drawingViewController.h"
#import "myview.h"
@implementation drawingViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect rect = CGRectMake(0,0,340,480);  
    myview *ui = [[myview alloc] initWithFrame:rect];
    [self.view addSubview:ui];
}

#import <UIKit/UIKit.h>
@interface myview : UIView {
}
@end

#import "myview.h"
@implementation myview
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code.
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextAddArc(context, 50, 50, 50, 0, 30, 0);
CGContextFillPath(context);

    //set the fill or stroke color
    CGContextSetRGBFillColor(context, 1, 0.5, 0.5, 1.0);
    CGContextSetRGBStrokeColor(context, 0.5, 1, 0.5, 1.0);

    //fill or draw the path
    CGContextDrawPath(context, kCGPathStroke);
    CGContextDrawPath(context, kCGPathFill);

    ------------------------------
    CGContextAddArc(context, 100, 100, 20, 0, 30, 0);

    //set the fill or stroke color
    CGContextSetRGBFillColor(context, 1, 0.5, 0.5, 1.0);
    CGContextSetRGBStrokeColor(context, 0.5, 1, 0.5, 1.0);

    //fill or draw the path
    CGContextDrawPath(context, kCGPathStroke);
    CGContextDrawPath(context, kCGPathFill);

}

其他注意事项:

Drawing triangle/arrow on a line with CGContext

CGContext Optimization

iPhone clear CGContext

Saving and restoring CGContext

How do I draw a line on the iPhone?

How to draw string in other device orientations using CGContext iOS

1 个答案:

答案 0 :(得分:0)

<。>文件中的

#import <QuartzCore/QuartzCore.h>
@interface YourView : UIView {

...

<。>文件中的

- (void)drawRect:(CGRect)rect{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //your drawings
}

然后调用setNeedsDisplay重绘rect

相关问题