今天寫寫swift的基礎畫圖,菜鳥直接copy就可以啦,都是我自己代碼驗證過的。
1.首先定義一個繼承UIView自的類,複寫drawRect(rect:CGRect)方法,在方法裏面獲取畫筆.
let context:CGContextRef = UIGraphicsGetCurrentContext()!;//獲取畫筆上下文
CGContextSetAllowsAntialiasing(context, true)//抗鋸齒設置
在使用時直接傳入一個CGRect作爲參數創建對象,使用addSubview加入你的頁面view.
CGContextSetLineWidth(context,0.5)//設置畫筆寬度
CGContextSetStrokeColorWithColor(context,UIColor(red:204/255, green: 204/255, blue: 204/255, alpha:1).CGColor)//設置畫筆顏色
CGContextMoveToPoint(context, 0, 0); // 直線起點
CGContextAddLineToPoint(context, rect.size.width,0); // 直線終點
CGContextStrokePath(context) //關閉路徑,渲染
3.畫三角形
let sPoints = [CGPointMake(0 , 0),CGPointMake(10, 10),CGPointMake(20, 0)];
CGContextAddLines(context, sPoints,3); //添加線
CGContextClosePath(context); //關閉路徑
CGContextDrawPath(context, CGPathDrawingMode.FillStroke)//根據座標繪製路徑
爲什麼要把三角形放在直線後呢,因爲這樣就可以完成一個帶箭頭的直線啦
4.畫圖片
畫圖片這個必須要說下,如果按傳統寫法:CGContextDrawImage(context, rect, image)來畫的畫,你會發現圖片都是倒立的,哈哈,據說人家的座標系是y軸向下的
所以如果你和我一樣有這種困擾,按如下方式轉換一下,就可以啦!
class func drawImage(context:CGContextRef, image:CGImageRef, rect:CGRect){
CGContextSaveGState(context);
CGContextTranslateCTM(context, rect.origin.x, rect.origin.y);
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
CGContextDrawImage(context, rect, image);
CGContextRestoreGState(context);
}
5.畫字符串
畫字符串時候會碰到一個問題,就是居中對齊,腦子有洞的時候,我們會使用drawAtPoint這個方法,計算出字符串的物理長度,然後去計算一個值作爲起點,使他能夠實現真正的居中對齊。遇到需要分行每行都居中的時候,就傻了。
其實還有一種思路哇,就是給他所有能用的空間,讓他自己去居中就好噠
let font = UIFont.systemFontOfSize(12 *CGFloat(Const.FONTSCANLE))
let color = UIColor.blackColor()
let style =NSMutableParagraphStyle()
style.alignment =NSTextAlignment.Left
(str asNSString).drawInRect(rect1, withAttributes: [NSFontAttributeName:font,NSForegroundColorAttributeName:color,NSParagraphStyleAttributeName:style])
順便提一下withAttributes,可以用來設置字體顏色,字體大小,以及偏移屬性。