美文网首页iOS开发
iOS 在控件上添加虚线边框

iOS 在控件上添加虚线边框

作者: 失心F | 来源:发表于2017-08-07 15:11 被阅读14次

    http://www.jianshu.com/p/12b439443b3b

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

    CAShapeLayer*border = [CAShapeLayerlayer];//虚线的颜色border.strokeColor = [UIColorredColor].CGColor;//填充的颜色border.fillColor = [UIColorclearColor].CGColor;//设置路径border.path = [UIBezierPathbezierPathWithRect: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];

    效果1

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

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

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

    效果2

    以为要在控件上添加圆角

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

    然而效果依然很奇怪。

    效果3

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

    最终

    下面全部代码

    CAShapeLayer*border = [CAShapeLayerlayer];//虚线的颜色border.strokeColor = [UIColorredColor].CGColor;//填充的颜色border.fillColor = [UIColorclearColor].CGColor;UIBezierPath*path = [UIBezierPathbezierPathWithRoundedRect: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];

    作者:闹钟先生的闹钟

    链接:http://www.jianshu.com/p/12b439443b3b

    來源:简书

    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    相关文章

      网友评论

        本文标题:iOS 在控件上添加虚线边框

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