一、重寫drawRect方法。
- (void)drawRect:(CGRect)rect { [super drawRect:rect]; CGContextRef currentContext = UIGraphicsGetCurrentContext(); //設置虛線顏色 CGContextSetStrokeColorWithColor(currentContext, [UIColor BlackColor].CGColor); //設置虛線寬度 CGContextSetLineWidth(currentContext, 1); //設置虛線繪制起點 CGContextMoveToPoint(currentContext, 0, 0); //設置虛線繪制終點 CGContextAddLineToPoint(currentContext, self.frame.origin.x + self.frame.size.width, 0); //設置虛線排列的寬度間隔:下面的arr中的數字表示先繪制3個點再繪制1個點 CGFloat arr[] = {3,1}; //下面最後一個參數“2”代表排列的個數。 CGContextSetLineDash(currentContext, 0, arr, 2); CGContextDrawPath(currentContext, kCGPathStroke); }
二、采用CAShapeLayer方式繪制虛線
CAShapeLayer *shapeLayer = [CAShapeLayer layer]; [shapeLayer setBounds:self.bounds]; [shapeLayer setPosition:CGPointMake(self.frame.size.width / 2.0, self.frame.size.height)]; [shapeLayer setFillColor:[UIColor clearColor].CGColor]; //設置虛線顏色 shapeLayer setStrokeColor:[UIColor BlackColor].CGColor]; //設置虛線寬度 [shapeLayer setLineWidth:self.frame.size.height]; [shapeLayer setLineJoin:kCALineJoinRound]; //設置虛線的線寬及間距 [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:3], [NSNumber numberWithInt:1], nil]]; //創建虛線繪制路徑 CGMutablePathRef path = CGPathCreateMutable(); //設置虛線繪制路徑起點 CGPathMoveToPoint(path, NULL, 0, 0); //設置虛線繪制路徑終點 CGPathAddLineToPoint(path, NULL, self.frame.size.width, 0); //設置虛線繪制路徑 [shapeLayer setPath:path]; CGPathRelease(path); //添加虛線 [self.layer addSublayer:shapeLayer];
關於這種方式已經有人整理出了一個非常好用的類方法,具體見下面這段代碼,注意:下面非完整代碼,如有需要,請自己百度搜索。
/** ** lineView: 需要繪制成虛線的view ** lineLength: 虛線的寬度 ** lineSpacing: 虛線的間距 ** lineColor: 虛線的顏色 **/ + (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor { CAShapeLayer *shapeLayer = [CAShapeLayer layer]; ..... [shapeLayer setStrokeColor:lineColor.CGColor]; ...... [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]]; ...... [lineView.layer addSublayer:shapeLayer]; }
三、經濟實惠型:采用貼圖的方式繪制虛線(需要設計師切圖配合)
UIImageView *imgDashLineView =[[UIImageView alloc] initWithFrame:CGRectMake(15, 200, self.view.frame.size.width - 30, 1)]; [imgDashLineView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"xuxian.png"]]]; [self.view addSubview:imgDashLineView];
總結
以上內容部分來自於網絡,本著分享的學習精神,如有涉及侵權問題,請及時告知。以上就是這篇文章的全部內容,歡迎大家一起探討學習,有問題請留言,小編將會盡快對你的問題進行回復。