iOS竖直虚线画法

项目中有画水平虚线和竖直虚线的需求,便在网上参考了别人的水平虚线画法,子类化了竖直虚线的DashLineView

DashLineView.h

@interface DashLineView : UIView
- (instancetype)initWithFrame:(CGRect)frame withLineLength:(NSInteger)lineLength withLineSpacing:(NSInteger)lineSpacing withLineColor:(UIColor *)lineColor;
@end

DashLineView.m

- (instancetype)initWithFrame:(CGRect)frame withLineLength:(NSInteger)lineLength withLineSpacing:(NSInteger)lineSpacing withLineColor:(UIColor *)lineColor{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _lineLength = lineLength;
        _lineSpacing = lineSpacing;
        _lineColor = lineColor;
        _height = frame.size.height;
    }
    return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    CGContextSetLineWidth(context,1);
    CGContextSetStrokeColorWithColor(context, _lineColor.CGColor);
    CGFloat lengths[] = {_lineLength,_lineSpacing};
    CGContextSetLineDash(context, 0, lengths,2);
    CGContextMoveToPoint(context, 0, 0);
    CGContextAddLineToPoint(context, 0,_height);
    CGContextStrokePath(context);
    CGContextClosePath(context);
}
//竖向的虚线
DashLineView *verticalDashLine = [[DashLineView alloc] initWithFrame:CGRectMake(kScreen_Width/2, 75+15, 0.5, 25) withLineLength:6 withLineSpacing:3 withLineColor:[UIColor colorWithHexString:LineGrayColor]];
[self.contentView addSubview:verticalDashLine];

iOS竖直虚线画法_第1张图片
dashline.png

DEMO地址: https://github.com/zhangjiahuan8888/HHDashLine
更多源码请访问github: https://github.com/zhangjiahuan8888

你可能感兴趣的:(iOS竖直虚线画法)