IOS绘制虚线的方法总结

一、重写drawRect方法

    - (void)drawRect:(CGRect)rect
    {
     [super drawRect:rect];
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    //设置虚线颜色
     CGContextSetStrokeColorWithColor(currentContext, [UIColor     BlackColor].CGColor);
     //设置虚线宽度
     CGContextSetLineWidth(currentContext, 1);
     //设置虚线绘制起点
     CGContextMoveToPoint(currentContext, 0, 0);
     //设置虚线绘制终点
     CGContextAddLineToPoint(currentContext, self.frame.origin.x + self.frame.size.width, 0);
     //设置虚线排列的宽度间隔:下面的arr中的数字表示先绘制3个点再绘制1个点
     CGFloat arr[] = {3,1};
     //下面最后一个参数“2”代表排列的个数。
     CGContextSetLineDash(currentContext, 0, arr, 2);
     CGContextDrawPath(currentContext, kCGPathStroke);
    }

二、采用CAShapeLayer方式绘制虚线

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:self.bounds];
    [shapeLayer setPosition:CGPointMake(self.frame.size.width / 2.0,       self.frame.size.height)];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //设置虚线颜色
    shapeLayer setStrokeColor:[UIColor BlackColor].CGColor];
    //设置虚线宽度
    [shapeLayer setLineWidth:self.frame.size.height];
    [shapeLayer setLineJoin:kCALineJoinRound];
    //设置虚线的线宽及间距
     [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber       numberWithInt:3], [NSNumber numberWithInt:1], nil]];
     //创建虚线绘制路径
     CGMutablePathRef path = CGPathCreateMutable();
     //设置虚线绘制路径起点
     CGPathMoveToPoint(path, NULL, 0, 0);
     //设置虚线绘制路径终点
      CGPathAddLineToPoint(path, NULL, self.frame.size.width, 0);
       //设置虚线绘制路径
     [shapeLayer setPath:path];
     CGPathRelease(path);
     //添加虚线
     [self.layer addSublayer:shapeLayer];

三、经济实惠型:采用贴图的方式绘制虚线(需要设计师切图配合)

      UIImageView *imgDashLineView =[[UIImageView alloc] initWithFrame:CGRectMake(15, 200, self.view.frame.size.width - 30, 1)];
    [imgDashLineView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage         imageNamed:@"xuxian.png"]]];
      [self.view addSubview:imgDashLineView];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录: 主要绘图框架介绍 CALayer 绘图 贝塞尔曲线-UIBezierPath CALayer子类 补充:i...
    Ryan___阅读 5,637评论 1 9
  • 转载:http://www.jianshu.com/p/32fcadd12108 每个UIView有一个伙伴称为l...
    F麦子阅读 11,472评论 0 13
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,204评论 4 61
  • 和我聊过天的人们都说 “诶,我觉得你吧,离成人只差一步,但是比小孩懂事多了,是不是这样?” 是吗?我也搞不懂我自己...
    暖暖的猫七啊阅读 1,189评论 0 0
  • Hydra 是一个 Swift 3 编写的异步框架, 它轻量级并且支持几乎所有的异步方法 like always,...
    阿瑟李阅读 4,119评论 0 3