用这个方法画图,主要是使用Layer 层画图
显示创建两个类,一个是继承于UIView,一个是继承于CALayer,其中需要现在viewController中添加一个画布:
DrawView *drawView = [[DrawView alloc]initWithFrame:CGRectMake(20, 140, 200, 200)];
drawView.backgroundColor = [UIColor grayColor];
[self.view addSubview:drawView];
再就是在继承于UIView的类中添加构造函数
- ( id )initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
DrawLayer *drawLayer = [[DrawLayer alloc]init];
drawLayer.frame = CGRectMake(20, 140, frame.size.width/2, frame.size.width/2);
drawLayer.backgroundColor = [UIColor redColor].CGColor;
[self.layer addSublayer:drawLayer];
[drawLayer setNeedsDisplay];
}
return self;
}
在写调用layer层的函数
- ( void )drawRect:(CGRect)rect{
[super drawRect:rect];
}
最后是在继承于CALayer的类中绘制各种图形:
- ( void )drawInContext:(CGContextRef)ctx(这个方法不用获取上下文){
CGContextAddArc(ctx, 100 , 100, 80, 0, 2*M_PI, 0);
CGContextStrokePath(ctx);
}