美文网首页
UIBezierPath的setLineDash与CAShape

UIBezierPath的setLineDash与CAShape

作者: _RG | 来源:发表于2019-11-08 17:48 被阅读0次

使用UIBezierPath绘制虚线时, 需要制定上下文才能绘制出来, 也就是需要在- (void)drawRect:(CGRect)rect 方法里面进行绘制

例如

- (void)drawRect:(CGRect)rect {
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 10)];
    [path addLineToPoint:CGPointMake(100, 80)];
    path.lineWidth = 2;
    [[UIColor orangeColor] set];
    CGFloat dash[] = {8.0,3.0,16.0,7.0};
    [path setLineDash:dash count:4 phase:7];
    [path stroke];
}

如果不在- (void)drawRect:(CGRect)rect方法里面进行绘制,则无法绘制出虚线,

但可以使用CAShapeLayer进行绘制, setLineDashPattern就行传递一个包含NSNumber类型的数组, 第一个NSNumber是虚线的长度, 第二个NSNumber是虚线之间的间隔

 TestView *view = [[TestView alloc] initWithFrame:CGRectMake(50, 100, 300, 200)];
    [self.view addSubview:view];
    view.backgroundColor = [UIColor grayColor];
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(10, 10)];
    [path addLineToPoint:CGPointMake(180, 10)];
    
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor redColor].CGColor;
    layer.lineWidth = 1;
    [layer setLineDashPattern:@[[NSNumber numberWithInt:10],[NSNumber numberWithInt:5]]];
    [view.layer addSublayer:layer];

相关文章

网友评论

      本文标题:UIBezierPath的setLineDash与CAShape

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