canvas教程

-drawRect学习总结

字号+ 作者:H5之家 来源:H5之家 2015-10-21 19:26 我要评论( )

-drawRect学习总结,drawRect是UIView的一个方法,用于View的绘制操作。先贴上一段代码:CustomView.m-(void)drawRect:(CGRect)rect{CGContextRefcontext=UIGraph

助理编辑-drawRect学习总结

  [  中国学网   ]     |  责编:崔宁

返回首页 分享到

        drawRect是UIView的一个方法,用于View的绘制操作。先贴上一段代码:


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方法就是在这块画布上作图。



相关信息

分享到:

网友评论

返回开发技术频道今日最新

  • 猜你喜欢
  • 今日最新
  • 本文相关搜索

    精彩推荐 查看更多...

    热门搜索排行榜

     

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    相关文章
    • 学习慕课网canvas倒计时实例笔记

      学习慕课网canvas倒计时实例笔记

      2017-04-30 14:01

    • 从一个画板demo学习canvas

      从一个画板demo学习canvas

      2017-04-30 13:00

    • canvas游戏开发学习之四:应用图像

      canvas游戏开发学习之四:应用图像

      2017-04-29 16:00

    • JS canvas学习笔记

      JS canvas学习笔记

      2017-04-29 15:03

    网友点评