#import <UIKit/UIKit.h>
@interface DashesLineView : UIView
@property(nonatomic)CGPoint startPoint;//虛線起點
@property(nonatomic)CGPoint endPoint;//虛線終點
@property(nonatomic,strong)UIColor *lineColor;//虛線顏色
@end
#import "DashesLineView.h"
@implementation DashesLineView
- (id)initWithFrame:(CGRect)frame
{
self= [super initWithFrame:frame];
if(self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context,0.5);//線寬度
CGContextSetStrokeColorWithColor(context,self.lineColor.CGColor);
CGFloat lengths[] = {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
drawRect在以下情況下會被調用:
1、如果在UIView初始化時沒有設置rect大小,將直接導致drawRect不被自動調用。drawRect 掉用是在Controller->loadView, Controller->viewDidLoad 兩方法之后掉用的.所以不用擔心在 控制器中,這些View的drawRect就開始畫了.這樣可以在控制器中設置一些值給View(如果這些View draw的時候需要用到某些變量 值).
2、該方法在調用sizeToFit后被調用,所以可以先調用sizeToFit計算出size。然后系統自動調用drawRect:方法。
3、通過設置contentMode屬性值為UIViewContentModeRedraw。那么將在每次設置或更改frame的時候自動調用drawRect:。
4、直接調用setNeedsDisplay,或者setNeedsDisplayInRect:觸發drawRect:,但是有個前提條件是rect不能為0。
以上1,2推薦;而3,4不提倡
drawRect方法使用注意點:
1、 若使用UIView繪圖,只能在drawRect:方法中獲取相應的contextRef並繪圖。如果在其他方法中獲取將獲取到一個invalidate 的ref並且不能用於畫圖。drawRect:方法不能手動顯示調用,必須通過調用setNeedsDisplay 或 者 setNeedsDisplayInRect,讓系統自動調該方法。
2、若使用calayer繪圖,只能在drawInContext: 中(類似魚drawRect)繪制,或者在delegate中的相應方法繪制。同樣也是調用setNeedDisplay等間接調用以上方法
3、若要實時畫圖,不能使用gestureRecognizer,只能使用touchbegan等方法來掉用setNeedsDisplay實時刷新屏幕