1. 程式人生 > >iOS 開發 繪製虛線

iOS 開發 繪製虛線

/**
 ** lineView:      需要繪製成虛線的view
 ** lineLength:  虛線的寬度
 ** lineSpacing:    虛線的間距
 ** lineColor:    虛線的顏色
 **/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
  CAShapeLayer *shapeLayer = [CAShapeLayer layer];
  [shapeLayer setBounds:lineView.bounds];
  [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2
, CGRectGetHeight(lineView.frame))]; [shapeLayer setFillColor:[UIColor clearColor].CGColor]; // 設定虛線顏色為blackColor [shapeLayer setStrokeColor:lineColor.CGColor]; // 設定虛線寬度 [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)]; [shapeLayer setLineJoin:kCALineJoinRound]; // 設定線寬,線間距 [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]]; // 設定路徑
CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 0, 0); CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0); [shapeLayer setPath:path]; CGPathRelease(path); // 把繪製好的虛線新增上來 [lineView.layer addSublayer:shapeLayer]; }