美文网首页
温故知新---iOS给视图加虚线边框

温故知新---iOS给视图加虚线边框

作者: 没八阿哥的程序 | 来源:发表于2018-01-05 14:32 被阅读25次

这个功能一般用的不多,但不免碰到有提出这样需求的。

效果: 加圆角虚线后

废话不多说,上代码:

CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.bounds = CGRectMake(0, 0, viewWidth, viewHeight);
    borderLayer.position = CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds));
    borderLayer.path = [UIBezierPath bezierPathWithRoundedRect:borderLayer.bounds cornerRadius:8].CGPath;
    borderLayer.lineWidth = 1. / [[UIScreen mainScreen] scale];
    borderLayer.lineDashPattern = @[@4, @4];
    borderLayer.fillColor = [UIColor clearColor].CGColor;
    borderLayer.strokeColor = [UIColor redColor].CGColor;
    [view.layer addSublayer:borderLayer];

可以封装一个方法,不用对每一个View都写这段代码

-(void)addDottedBorderWithView:(UIView*)view{
    CGFloat viewWidth = view.mj_w;
    CGFloat viewHeight = view.mj_h;
    view.layer.cornerRadius = 8;
    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.bounds = CGRectMake(0, 0, viewWidth, viewHeight);
    borderLayer.position = CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds));
    borderLayer.path = [UIBezierPath bezierPathWithRoundedRect:borderLayer.bounds cornerRadius:8].CGPath;
    borderLayer.lineWidth = 1. / [[UIScreen mainScreen] scale];
    borderLayer.lineDashPattern = @[@4, @4];
    borderLayer.fillColor = [UIColor clearColor].CGColor;
    borderLayer.strokeColor = [UIColor redColor].CGColor;
    [view.layer addSublayer:borderLayer];
}

用到的时候直接把相应的View传过来就行了 。

相关文章

网友评论

      本文标题:温故知新---iOS给视图加虚线边框

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