http://www.itdecent.cn/p/12b439443b3b
以按鈕為例子,實(shí)現(xiàn)虛線按鈕:
CAShapeLayer*border = [CAShapeLayerlayer];//虛線的顏色border.strokeColor = [UIColorredColor].CGColor;//填充的顏色border.fillColor = [UIColorclearColor].CGColor;//設(shè)置路徑border.path = [UIBezierPathbezierPathWithRect: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;
然而效果是這樣子的,四個(gè)角變的很奇怪

效果2
以為要在控件上添加圓角
self.lineButton.layer.cornerRadius =5.f;self.lineButton.layer.masksToBounds =YES;
然而效果依然很奇怪。

效果3
最后找資料終于得到實(shí)現(xiàn)效果 需要把bezierPathWithRect 替換成 bezierPathWithRoundedRect 就可以了

最終
下面全部代碼
CAShapeLayer*border = [CAShapeLayerlayer];//虛線的顏色border.strokeColor = [UIColorredColor].CGColor;//填充的顏色border.fillColor = [UIColorclearColor].CGColor;UIBezierPath*path = [UIBezierPathbezierPathWithRoundedRect: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];
作者:鬧鐘先生的鬧鐘
鏈接:http://www.itdecent.cn/p/12b439443b3b
來源:簡(jiǎn)書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。