美文网首页
IOS 画虚线方法

IOS 画虚线方法

作者: leonardni | 来源:发表于2017-07-07 00:12 被阅读413次

使用CGContext 绘图方法

1.重写draw rect 方法:

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    CGContextSetLineWidth(context,2.0f);//线宽度这里是像素大小
    CGContextSetStrokeColorWithColor(context,[UIColor blueColor].CGColor);
    CGFloat lengths[] = {1,3};//先画2个点再画2个点
    CGContextSetLineDash(context,0, lengths,2);//注意2(count)的值等于lengths数组的长度
    CGContextMoveToPoint(context,0,0);
    CGContextAddLineToPoint(context,self.frame.size.width / 2.0f,0);
    CGContextStrokePath(context);
    CGContextClosePath(context);
}

iOS 画虚线方法总结 作者有提到另外一种方法叫通过UIImage的绘图方法来绘制 的这种方法,其实还是通过CGContext 的方式绘制曲线。

具体CGContext 相关的内容可见:
apple 官网

IOS开发之——绘图(CGContext)

例子请见

iOS CGContextRef的使用

通过CAShapeLayer方式绘制虚线

2.通过CAShapeLayer方式绘制虚线

/**
 ** 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];
}

相关文章

  • IOS 画虚线方法

    使用CGContext 绘图方法 1.重写draw rect 方法: iOS 画虚线方法总结 作者有提到另外一种方...

  • iOS开发绘制虚线的方法

    iOS开发绘制虚线的方法 方法一:通过Quartz 2D 在 UIView drawRect:方法进行绘制虚线 -...

  • iOS Xib画虚线方法

    代码设置尺寸 xib设置类型! Xib添加虚线

  • iOS 画虚线方法总结

    前言 好几天都没有写简书了,主要是最近一直在做原型图,六天的时间出了两个项目的原型(PC+手机),结果累成狗,发现...

  • 绘制实线 曲线的矩形框

    主要是讲画虚线,有个需求给按钮添加虚线的边框 一开始想到是下面 这样的方法 但是发现这个方法没办法画虚线 然使用下...

  • iOS 画虚线

    其中的一个方法 /***画虚线@param lineView 视图@param lineLength 单个虚线大小...

  • iOS 画虚线

    通过Quartz2D画虚线

  • iOS 画虚线

    创建一个UIView的子类,在drawRect:(CGRect)rect里

  • iOS 画虚线

    在所需要的view上画一条虚线,重写下面的方法即可 -(void)drawRect:(CGRect)rect{ [...

  • IOS画虚线

    UIImageView*imageView1 = [[UIImageViewalloc]initWithFrame...

网友评论

      本文标题:IOS 画虚线方法

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