iOS-虚线Category

实际项目中已用到  绝对可用。记录下来方便以后查阅

.h

#import <UIKit/UIKit.h>

typedef NS_ENUM(NSInteger, DashLineType) {

    VerticalDashLine,

    HorizontalDashLine

};

@interface UIView (DashLine)

+ (void)drawDashLine:(UIView *)lineView thickness:(int)thickness lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor andDashLineType:(DashLineType)dashLineType;

@end

.m

#import "UIView+DashLine.h"

@implementation UIView (DashLine)

/**

** lineView:      需要绘制成虚线的view

** thickness:      虚线的粗细大小

** lineSpacing:    虚线的间距

** lineColor:      虚线的颜色

** dashLineType    类型:竖线还是横线

**/

+ (void)drawDashLine:(UIView *)lineView thickness:(int)thickness lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor andDashLineType:(DashLineType)dashLineType

{

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    [shapeLayer setBounds:lineView.bounds];

    if (dashLineType == VerticalDashLine) { //竖线

        [shapeLayer setPosition:CGPointMake(0, CGRectGetHeight(lineView.frame)/2)];

    }else { //横线

        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame)/2, 0)];

    }

    [shapeLayer setFillColor:[UIColor clearColor].CGColor];

    //  设置虚线颜色

    [shapeLayer setStrokeColor:lineColor.CGColor];

    //  设置虚线粗细大小

    [shapeLayer setLineWidth:thickness];

    [shapeLayer setLineJoin:kCALineJoinRound];

    //  设置线间距

    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineSpacing], [NSNumber numberWithInt:lineSpacing], nil]];

    //  设置路径

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, NULL, 0, 0);

    CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), CGRectGetHeight(lineView.frame));

    [shapeLayer setPath:path];

    CGPathRelease(path);

    //  把绘制好的虚线添加上来

    [lineView.layer addSublayer:shapeLayer];

}

@end


竖虚线

//CGRectMake(100, 10, 1, 80)       绘制出来的虚线为(x,y):   (100,10)到(100,10+80)的竖虚线

UIView *dashlineView = [[UIView alloc]initWithFrame:CGRectMake(100, 10, 1, 80)];

[UIView drawDashLine:dashlineView thickness:1 lineSpacing:3 lineColor:[UIColor grayColor] andDashLineType:VerticalDashLine];

[self.view addSubview:dashlineView];

横虚线

//CGRectMake(20, 150, 200, 1)       绘制出来的虚线为(x,y):   (20,150)到(20,150+200)的横虚线

UIView *dashLineView = [[UIView alloc]initWithFrame:CGRectMake(20, 150, 200, 1)];

[UIView drawDashLine:dashLineView thickness:1 lineSpacing:3 lineColor:[UIColor grayColor] andDashLineType:HorizontalDashLine];

[self.view addSubview:dashLineView];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容