-drawRect学习总结
2015-10-14 15:48
369 查看
drawRect是UIView的一个方法,用于View的绘制操作。先贴上一段代码:
CustomView.m
CustomView.m
- (void)drawRect:(CGRect)rect{ CGContextRef context=UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 2); CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); CGContextMoveToPoint(context, 0, 0); CGContextAddLineToPoint(context, rect.size.width, 0); CGContextAddLineToPoint(context, rect.size.width, rect.size.height); CGContextAddLineToPoint(context, 0, rect.size.height); CGContextAddLineToPoint(context, 0, 0); CGContextStrokePath(context); }1、CustomView继承自UIView,并重写drawRect方法进行自定义绘制。2、在drawRect方法里,绘制的主要流程如下:(1)获得绘制上下文
CGContextRef context=UIGraphicsGetCurrentContext();(2)设置线条(画笔)属性。这里只设置了线条颜色和粗细。
CGContextSetLineWidth(context, 2); CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);(3)设置绘制的路线。
CGContextMoveToPoint(context, 0, 0); CGContextAddLineToPoint(context, rect.size.width, 0); CGContextAddLineToPoint(context, rect.size.width, rect.size.height); CGContextAddLineToPoint(context, 0, rect.size.height); CGContextAddLineToPoint(context, 0, 0);(4)绘制。
CGContextStrokePath(context);3、drawRect方法一般只会执行一次,如果要多次重绘,需要调用setNeedsDisplay或setNeedsDisplayInRect,如:
CustomView *cView=[[CustomView alloc] initWithFrame:CGRectMake(100, 200, 200, 200)]; cView.backgroundColor=[UIColor redColor]; [bgView addSubview:cView]; [cView performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:5.0f];//5s后重绘4、如果一开始初始化CustomView时未设置frame,则drawRect不会被调用。5、绘图上下文(CGContextRef)只有在drawRect才有效,即以下代码只有在drawRect中才会获得正确的context,其他地方及时调用了也不回有结果。
CGContextRef context=UIGraphicsGetCurrentContext();6、绘图上下文就是指当前的CustomView,可以把CustomView想象成一个画布,drawRect方法就是在这块画布上作图。
相关文章推荐
- android drawRect(a,b,c,d,paint)方法解释
- CGContextRef 实现简易涂鸦板
- iOS中drawRect方法实现画圆角矩形,顺时针和逆时针
- UIView的layoutSubviews和drawRect方法何时调用
- 重写drawRect:方法后,无法修改背景颜色问题
- Android targetSdkVersion引起的问题
- 2D画图 & CGContextRef 常用的函数和方法
- CGColorRef & CGGradientRef
- 一张图看懂ios drawRect
- ios 画图
- iOS开发系列--打造自己的“美图秀秀”
- UIView的layoutSubviews和drawRect方法何时调用
- UIView中的drawRect
- layoutSubviews和drawRect何时调用?
- IOS用CGContextRef画各种图形
- 重写drawRect方法 CGContext的使用
- iOS 绘图(drawrect)图片裁剪的红色框框
- 熟悉下CGContextRef
- CGContextRef用法
- 绘图相关