閑著沒事钉鸯,在看項目中同事做的統(tǒng)計圖表的代碼,之前一直美做過這些東西邮辽,所以自己寫了個Demo玩一玩唠雕,代碼會都分享出來,直接復制粘貼就可以用吨述,太簡單岩睁。
在寫Demo之前我先百度了"CGContextRef",幾乎都是一篇文章復制粘貼的揣云,好傷心的說捕儒。
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font NS_DEPRECATED_IOS(2_0, 7_0, "Use -drawInRect:withAttributes:") __TVOS_PROHIBITED;
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font這個方法早就過時了好伐,竟然還有這么多文章在說這個邓夕。官方寫的很清楚啦刘莹,用drawInRect:withAttributes:就好了。
既然說寫字焚刚,那就先寫個字吧点弯。 畫字。
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont systemFontOfSize:15.0];
NSDictionary *atDic = @{NSFontAttributeName:font,NSForegroundColorAttributeName:color};
[@"我是文字" drawInRect:CGRectMake(10, 20, 80, 20) withAttributes: atDic];
// TODO:
可是汪榔,我卻沒看出這個和CGContextRef有啥關系蒲拉,我沒研究很深,就是在字面上看的痴腌,以后明白了會改正的雌团。
中間插一句,CGContextRef相當于在紙上畫畫士聪,當然就要先有張畫紙锦援,也就是View,不要傻乎乎的卸載控制器里面剥悟,什么都不顯示還想不通啥原因灵寺。
- 畫一段弧線
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor); // 填充色
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); // 軌跡顏色
CGContextSetLineWidth(context, 20); // 軌跡寬度
CGContextAddArc(context, 100, 200, 80, -90 * M_PI / 180, 0.75 * M_PI / 180, 1); // 第二個參數(shù):中心橫坐標曼库,第三個參數(shù):中心縱坐標,第四個參數(shù):半徑略板,第五個參數(shù):從哪開始毁枯,第六個參數(shù):到哪結束,最后一個參數(shù):0:順時針叮称,1:逆時針
// CGContextStrokePath(context); // 這是畫線种玛,也就是弧線。
// CGContextFillPath(context); // 這是填充顏色
CGContextDrawPath(context, kCGPathEOFillStroke); // 寫這句就可以有填充色瓤檐。
//繪制填充 CGPathDrawingMode是個枚舉類赂韵,kCGPathFill填充非零繞數(shù)規(guī)則 沒有邊框 ,kCGPathEOFill表示用奇偶規(guī)則 也沒有邊框 ,kCGPathStroke路徑 只有邊框 ,kCGPathFillStroke路徑填充 邊框和填充色都有 , kCGPathEOFillStroke表示描線,不是填充 邊框和填充色都有挠蛉。專業(yè)的解釋我不懂祭示,效果我都試過了。
其實能畫弧線也就可以畫圓了谴古,0-2π都畫上就是圓啊质涛。
最后就是這個效果
- 畫橢圓
CGContextAddEllipseInRect(context, CGRectMake(200, 200, 100, 40));
CGContextDrawPath(context, kCGPathFillStroke);
加這兩句就出現(xiàn)橢圓了,當然把兩軸的長度寫成一樣的就是圓了讥电。
- 畫三角形
CGPoint sPoints[3];//坐標點
sPoints[0] =CGPointMake(100, 400);//坐標1
sPoints[1] =CGPointMake(150, 400);//坐標2
sPoints[2] =CGPointMake(150, 320);//坐標3
CGContextAddLines(context, sPoints, 3);//添加線
CGContextClosePath(context);//封起來 沒有這句不會封口的
CGContextDrawPath(context, kCGPathFillStroke); //根據坐標繪制路徑
可以畫三角形之后蹂窖,多邊形都不是問題轧抗。
- 畫圓角矩形
float w = 200;
float h = 300;
CGContextMoveToPoint(context, w, h-20); // 開始坐標右邊開始
CGContextAddArcToPoint(context, w, h, w-20, h, 10); // 右下角角度
CGContextAddArcToPoint(context, 120, h, 120, h-20, 10); // 左下角角度
CGContextAddArcToPoint(context, 120, 250, w-20, 250, 10); // 左上角
CGContextAddArcToPoint(context, w, 250, w, h-20, 10); // 右上角
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke); //根據坐標繪制路徑
- 畫貝塞爾曲線
//二次曲線
CGContextMoveToPoint(context, 120, 300);//設置Path的起點
CGContextAddQuadCurveToPoint(context,190, 310, 120, 390);//設置貝塞爾曲線的控制點坐標和終點坐標
CGContextStrokePath(context);
//三次曲線函數(shù)
CGContextMoveToPoint(context, 200, 300);//設置Path的起點
CGContextAddCurveToPoint(context,250, 280, 250, 400, 280, 300);//設置貝塞爾曲線的控制點坐標和控制點坐標終點坐標
CGContextStrokePath(context);
差不多就這樣吧恩敌,以后再補充。