以按鈕為例子树酪,實(shí)現(xiàn)虛線按鈕:
CAShapeLayer *border = [CAShapeLayer layer];
//虛線的顏色
border.strokeColor = [UIColor redColor].CGColor;
//填充的顏色
border.fillColor = [UIColor clearColor].CGColor;
//設(shè)置路徑
border.path = [UIBezierPath bezierPathWithRect:self.lineButton.bounds].CGPath;
border.frame = self.lineButton.bounds;
//虛線的寬度
border.lineWidth = 1.f;
//設(shè)置線條的樣式
// border.lineCap = @"square";
//虛線的間隔
border.lineDashPattern = @[@4, @2];
[self.lineButton.layer addSublayer:border];
效果1
到這里基本已經(jīng)OK了根暑,但是突然發(fā)現(xiàn)我要的是有圓角的按鈕畸裳,那就去添加圓角
border.cornerRadius = 5.f;
border.masksToBounds = YES;
然而效果是這樣子的颇象,四個角變的很奇怪
效果2
以為要在控件上添加圓角
self.lineButton.layer.cornerRadius = 5.f;
self.lineButton.layer.masksToBounds = YES;
然而效果依然很奇怪蕴茴。
效果3
最后找資料終于得到實(shí)現(xiàn)效果 需要把bezierPathWithRect 替換成 bezierPathWithRoundedRect 就可以了
最終
下面全部代碼
CAShapeLayer *border = [CAShapeLayer layer];
//虛線的顏色
border.strokeColor = [UIColor redColor].CGColor;
//填充的顏色
border.fillColor = [UIColor clearColor].CGColor;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.lineButton.bounds cornerRadius:5];
//設(shè)置路徑
border.path = path.CGPath;
border.frame = self.lineButton.bounds;
//虛線的寬度
border.lineWidth = 1.f;
//設(shè)置線條的樣式
// border.lineCap = @"square";
//虛線的間隔
border.lineDashPattern = @[@4, @2];
self.lineButton.layer.cornerRadius = 5.f;
self.lineButton.layer.masksToBounds = YES;
[self.lineButton.layer addSublayer:border];