一、重寫(xiě)drawRect方法。
- (void)drawRect:(CGRect)rect{ [super drawRect:rect];CGContextRef currentContext = UIGraphicsGetCurrentContext();//設(shè)置虛線顏色 CGContextSetStrokeColorWithColor(currentContext, [UIColor BlackColor].CGColor); //設(shè)置虛線寬度 CGContextSetLineWidth(currentContext, 1); //設(shè)置虛線繪制起點(diǎn) CGContextMoveToPoint(currentContext, 0, 0); //設(shè)置虛線繪制終點(diǎn) CGContextAddLineToPoint(currentContext, self.frame.origin.x + self.frame.size.width, 0); //設(shè)置虛線排列的寬度間隔:下面的arr中的數(shù)字表示先繪制3個(gè)點(diǎn)再繪制1個(gè)點(diǎn) CGFloat arr[] = {3,1}; //下面最后一個(gè)參數(shù)“2”代表排列的個(gè)數(shù)。 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];//設(shè)置虛線顏色shapeLayer setStrokeColor:[UIColor BlackColor].CGColor];//設(shè)置虛線寬度[shapeLayer setLineWidth:self.frame.size.height];[shapeLayer setLineJoin:kCALineJoinRound];//設(shè)置虛線的線寬及間距 [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:3], [NSNumber numberWithInt:1], nil]]; //創(chuàng)建虛線繪制路徑 CGMutablePathRef path = CGPathCreateMutable(); //設(shè)置虛線繪制路徑起點(diǎn) CGPathMoveToPoint(path, NULL, 0, 0); //設(shè)置虛線繪制路徑終點(diǎn) CGPathAddLineToPoint(path, NULL, self.frame.size.width, 0); //設(shè)置虛線繪制路徑 [shapeLayer setPath:path]; CGPathRelease(path); //添加虛線 [self.layer addSublayer:shapeLayer];
關(guān)于這種方式已經(jīng)有人整理出了一個(gè)非常好用的類(lèi)方法,具體見(jiàn)下面這段代碼,注意:下面非完整代碼,如有需要,請(qǐng)自己百度搜索。
/** ** 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]; }
三、經(jīng)濟(jì)實(shí)惠型:采用貼圖的方式繪制虛線(需要設(shè)計(jì)師切圖配合)
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];
總結(jié)
以上內(nèi)容部分來(lái)自于網(wǎng)絡(luò),本著分享的學(xué)習(xí)精神,如有涉及侵權(quán)問(wèn)題,請(qǐng)及時(shí)告知。以上就是這篇文章的全部?jī)?nèi)容,歡迎大家一起探討學(xué)習(xí),有問(wèn)題請(qǐng)留言,小編將會(huì)盡快對(duì)你的問(wèn)題進(jìn)行回復(fù)。
新聞熱點(diǎn)
疑難解答
圖片精選