關於動畫的一些簡單應用。這里以畫直線為例。
繪圖的方法都是在UIView的drawRect中
執行的,對於一次性就能畫好的圖,直接使用drawRect即可,無需調用UIView的setNeedsDisplay。
但若想多次調用drawRect,即想做出動畫效果(如柱狀圖,效果是慢慢升起),術語叫重繪,那么就需要調用UIView的setNeedsDisplay方法。使用了setNeedsDisplay方法,程序會調用drawRect。類似於cellForRowAtIndexPath,無需在initWithFrame或viewDidLoad中調用,便可以直接被系統執行。
下面畫一條不規則的折線,沒有使用setNeedsDisplay。必要代碼
1 -(void)drawRect:(CGRect)rect{ 2 self.backgroundColor = [UIColor lightGrayColor]; 3 //獲得處理的上下文
4 CGContextRef context = UIGraphicsGetCurrentContext(); 5 //設置線的顏色
6 CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 7 //起始點設置為(0,0):注意這是上下文對應區域中的相對坐標,
8 CGContextMoveToPoint(context, 0, 0); 9 //設置下一個坐標點
10 CGContextAddLineToPoint(context, 100, 100); 11 //設置下一個坐標點
12 CGContextAddLineToPoint(context, 0, 150); 13 //設置下一個坐標點
14 CGContextAddLineToPoint(context, 50, 180); 15 //設置下一個坐標點
16 CGContextAddLineToPoint(context, 10, 18); 17 //連接上面定義的坐標點,也就是開始繪圖
18 CGContextStrokePath(context); 19 }
以下代碼是非必要的。關於線條的顏色設置也可以認為不必要
//設置線條樣式
CGContextSetLineCap(context, kCGLineCapSquare); //設置線條粗細寬度,默認為1.0
CGContextSetLineWidth(context, 1.0); //開始一個起始路徑
CGContextBeginPath(context);
效果如下

若想畫成柱狀圖,則只需用CGContextSetLineWidth把線畫粗點就可以了,要是折線圖也同理。
********************** 2015-09-16 補充 **********************
CADisplayLink是一個能將特定內容周期性繪制到屏幕上的定時器類,與NSTimer類似,但精確度比NSTimer高,適合做界面的不停重繪。需要注意下frameInterval的用法,表示每隔多少幀運行@selector的方法。用法如下:
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(toDoDrawLine)]; //frameInterval表示間隔多少幀運行一次@selector方法,默認是1,即每幀都調用一次
_displayLink.frameInterval = 3;
setNeedsDisplay為UIView的方法,當需要刷新view時,可調用該方法,setNeedsDisplay則會自動調用drawRect方法。
在drawRect方法中,需要獲取當前上下文,UIGraphicsGetCurrentContext一般情況下只用在drawRect方法中。context相當於畫布,可以在這上邊繪制圖形。
-(void)drawRect:(CGRect)rect{ //獲取當前上下文,UIGraphicsGetCurrentContext只能在drawRect里使用 //context相當於畫布,可以在這上邊繪制圖形
CGContextRef context = UIGraphicsGetCurrentContext(); [self drawBarWith:context]; }
繪制一些文本內容時,需要用drawInRect:withAttributes方法來設置文本的屬性。用法類似如下:
//文字屬性
UIFont *labelFont = [UIFont systemFontOfSize:15]; UIColor *labelColor = [UIColor blackColor]; //label文字的背景顏色。可設置為其它顏色
UIColor *labelBackColor = [UIColor clearColor]; //文字的段落樣式
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; style.alignment = NSTextAlignmentCenter; NSDictionary *dict = @{NSFontAttributeName:labelFont,NSForegroundColorAttributeName:labelColor,NSParagraphStyleAttributeName:style,NSBackgroundColorAttributeName:labelBackColor}; [@"標題A" drawInRect:CGRectMake(dataX, ViewHeight-15, _barPadding+_barWidth, 15) withAttributes:dict];
