美文网首页
iOS-虚线Category

iOS-虚线Category

作者: 是西一啊 | 来源:发表于2018-06-30 15:19 被阅读0次

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

    .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];

    相关文章

      网友评论

          本文标题:iOS-虚线Category

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