iOS 给UI控件画虚线(带圆角)

1、创建UIView分类  UIView+Extension.h

在.h文件 声明方法如下:

/**

 * 给UI控件画虚线

 * @param lineColor 虚线颜色

 * @param fillColor 填充色

 * @param radius 虚线圆角

 * @param lineWidth 虚线宽度

 * @param type 虚线类型  "butt", "round" and "square"

 * @return 返回 生成的虚线view

 */

- (UIView *)drawDotLineWithLineColor:(UIColor *)lineColor withFillColor:(UIColor *)fillColor withCornerRadius:(CGFloat)radius withLineWidth:(CGFloat)lineWidth AndLineType:(NSString *)type;



2、在.m文件 实现方法如下

//虚线

- (UIView *)drawDotLineWithLineColor:(UIColor *)lineColor withFillColor:(UIColor *)fillColor withCornerRadius:(CGFloat)radius withLineWidth:(CGFloat)lineWidth AndLineType:(NSString *)type {

    

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    

    shapeLayer.strokeColor = lineColor.CGColor;

    

    shapeLayer.fillColor = fillColor.CGColor;

    

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:radius];

    

    shapeLayer.path = path.CGPath;

    

    shapeLayer.frame = self.bounds;

    

    shapeLayer.lineWidth = lineWidth;

    

    if (type) {

        shapeLayer.lineCap = type;

    }else{

        shapeLayer.lineCap = @"square";

    }

    //虚线每段长度和间隔

    shapeLayer.lineDashPattern = @[@(2), @(2)];

    [self.layer addSublayer:shapeLayer];

    return self;

}

使用到虚线的时候 使用UI对象直接调用上面方法即可如:

[label drawDotLineWithLineColor:[UIColor redColor] withFillColor:[UIColor clearColor] withCornerRadius:2 withLineWidth:1 AndLineType:nil];





你可能感兴趣的:(随手笔记)