美文网首页
绘制虚线

绘制虚线

作者: osnail | 来源:发表于2019-03-30 11:10 被阅读0次

    方法一

    ····

    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    
    CGPoint p1 = CGPointMake(15, height-15);
    CGPoint p2 = CGPointMake(width - 15, height-15);
    //获得处理的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //设置颜色
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
    //设置线条粗细宽度
    CGContextSetLineWidth(context, 1);
    //起始点设置
    CGContextMoveToPoint(context, p1.x, p1.y);
    //设置下一个坐标点
    CGContextAddLineToPoint(context, p2.x, p2.y);
    //设置虚线排列的宽度间隔:下面的lengths中的数字表示先绘制3个点再绘制1个点
    CGFloat lengths[] = {5,3,5};
    //设置虚线 下面最后一个参数“3”代表排列的个数,即count的值等于lengths数组的长度
    CGContextSetLineDash(context, 0, lengths, 3);
    //连接上面定义的坐标点 设置线条样式
    CGContextDrawPath(context, kCGPathStroke);
    

    ····
    lengths的值{10,10}表示先绘制10个点,再跳过10个点,如此反复,如图:

    image.png

    如果把lengths值改为{10, 20, 10},则表示先绘制10个点,跳过20个点,绘制10个点,跳过10个点,再绘制20个点,如此反复,如图:


    image.png

    方法二

    /**
      ** lineView:       需要绘制成虚线的view
      ** lineLength:     虚线的宽度
      ** lineSpacing:    虚线的间距 
      ** lineColor:      虚线的颜色
      **/
    + (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
    {    
          CAShapeLayer *shapeLayer = [CAShapeLayer layer];
          [shapeLayer setBounds:lineView.bounds];
          [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];   
          [shapeLayer setFillColor:[UIColor clearColor].CGColor];  
          //  设置虚线颜色为blackColor    
          [shapeLayer setStrokeColor:lineColor.CGColor];   
          //  设置虚线宽度   
          [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];    
          [shapeLayer setLineJoin:kCALineJoinRound];    
          //  设置线宽,线间距
          [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];   
          //  设置路径    
          CGMutablePathRef path = CGPathCreateMutable();   
          CGPathMoveToPoint(path, NULL, 0, 0);  
          CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
          [shapeLayer setPath:path];    
          CGPathRelease(path);   
          //  把绘制好的虚线添加上来   
          [lineView.layer addSublayer:shapeLayer];
      }
    
    

    相关文章

      网友评论

          本文标题:绘制虚线

          本文链接:https://www.haomeiwen.com/subject/hjutmqtx.html