iOS開發 畫虛線
阿新 • • 發佈:2019-01-22
iOS中我們可以用一個UIView展示一條直線,但是虛線該怎麼實現呢
- (void)viewDidLoad { [super viewDidLoad]; // 要顯示虛線的view UIView *lineView = [[UIView alloc]init]; lineView.backgroundColor = [UIColor whiteColor]; lineView.frame = CGRectMake(0, 100, 320, 2); [self.view addSubview:lineView]; 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:[UIColor blackColor].CGColor]; // 設定虛線寬度 [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)]; [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, CGRectGetWidth(lineView.frame), 0); [shapeLayer setPath:path]; CGPathRelease(path); // 把繪製好的虛線新增上來 [lineView.layer addSublayer:shapeLayer]; }
本文由MiAo_EM原創文章,未經許可請勿轉載