0
点赞
收藏
分享

微信扫一扫

iOS 在控件上添加虚线边框

以按钮为例子,实现虚线按钮:

    CAShapeLayer *border = [CAShapeLayer layer];
    
    //虚线的颜色
    border.strokeColor = [UIColor redColor].CGColor;
    //填充的颜色
    border.fillColor = [UIColor clearColor].CGColor;
    
    //设置路径
    border.path = [UIBezierPath bezierPathWithRect:self.lineButton.bounds].CGPath;
    
    border.frame = self.lineButton.bounds;
    //虚线的宽度
    border.lineWidth = 1.f;
    
    
    //设置线条的样式
    //    border.lineCap = @"square";
    //虚线的间隔
    border.lineDashPattern = @[@4, @2];
    
    [self.lineButton.layer addSublayer:border];

到这里基本已经OK了,但是突然发现我要的是有圆角的按钮,那就去添加圆角

    border.cornerRadius = 5.f;
    
    border.masksToBounds = YES;

然而效果是这样子的,四个角变的很奇怪


以为要在控件上添加圆角

    self.lineButton.layer.cornerRadius = 5.f;
    self.lineButton.layer.masksToBounds = YES;

然而效果依然很奇怪。


最后找资料终于得到实现效果 需要把bezierPathWithRect 替换成 bezierPathWithRoundedRect 就可以了

下面全部代码

    CAShapeLayer *border = [CAShapeLayer layer];
    
    //虚线的颜色
    border.strokeColor = [UIColor redColor].CGColor;
    //填充的颜色
    border.fillColor = [UIColor clearColor].CGColor;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.lineButton.bounds cornerRadius:5];
    
    //设置路径
    border.path = path.CGPath;
    
    border.frame = self.lineButton.bounds;
    //虚线的宽度
    border.lineWidth = 1.f;
    
    
    //设置线条的样式
    //    border.lineCap = @"square";
    //虚线的间隔
    border.lineDashPattern = @[@4, @2];
    
    self.lineButton.layer.cornerRadius = 5.f;
    self.lineButton.layer.masksToBounds = YES;
    
    [self.lineButton.layer addSublayer:border];
举报

相关推荐

0 条评论