重寫drawRect方法
准備:繼承UIView的子類
.h文件
#import<UIKit/UIKit.h>
@interfaceDashesLineView :UIView
@property(nonatomic)CGPointstartPoint;//虛線起點
@property(nonatomic)CGPointendPoint;//虛線終點
@property(nonatomic,strong)UIColor* lineColor;//虛線顏色
@end
.m文件
#import"DashesLineView.h"
@implementationDashesLineView
- (id)initWithFrame:(CGRect)frame
{
self= [superinitWithFrame:frame];
if(self) {
// Initialization code
}
returnself;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
CGContextRefcontext =UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context,0.5);//線寬度
CGContextSetStrokeColorWithColor(context,self.lineColor.CGColor);
CGFloatlengths[] = {4,2};//先畫4個點再畫2個點
CGContextSetLineDash(context,0, lengths,2);//注意2(count)的值等於lengths數組的長度
CGContextMoveToPoint(context,self.startPoint.x,self.startPoint.y);
CGContextAddLineToPoint(context,self.endPoint.x,self.endPoint.y);
CGContextStrokePath(context);
CGContextClosePath(context);
}
@end