自定義了一個類 繼承了UIView 默認(rèn)帶了override func drawRect(rect: CGRect){} 系統(tǒng)會自動調(diào)用 接下來所有的繪圖都是在這里完成
import UIKit
class CustomView: UIView {
override func drawRect(rect: CGRect) {
drawcon()
//其它繪圖都是直接寫在這個函數(shù)體內(nèi),為了理順?biāo)悸泛兔烙^犹菇,所以排版的時候放在了外面
}
繪制表格 其中包含了繪圖的基本步驟
func drawcon(){
//1. 獲取上下文
let context = UIGraphicsGetCurrentContext()
var x:CGFloat = 50
while x < self.frame.size.width {
//2. 開始怕犁,設(shè)置繪制起點(diǎn)
CGContextMoveToPoint(context, x , 0)
//3. 終點(diǎn) 往上下文上添加圖形
CGContextAddLineToPoint(context, x, self.frame.size.height)
x += 50
}
var y :CGFloat = 50
while y < self.frame.size.height{
CGContextMoveToPoint(context, 0, y)
CGContextAddLineToPoint(context, self.frame.size.width, y)
y += 50
}
//4.保存當(dāng)前的上下文狀態(tài)
CGContextSaveGState(context)
//5. 設(shè)置顏色幅虑、樣式、尺寸
CGContextSetLineWidth(context, 2)
CGContextSetStrokeColor(context, [1,0,0,1])
//連接處設(shè)置
// CGContextSetLineJoin(cxt, .Round)
CGContextSetLineDash(context, 0, [4,5], 2)
//6.繪制
CGContextStrokePath(context)
//7.恢復(fù)到上次保存時的狀態(tài)
CGContextRestoreGState(context)
}
繪制矩形
context 環(huán)境都是在drawRect中 對象只有一個 如果設(shè)置了with為1那么整個過程就為1 所有為了解決這個問題 就利用圖形狀態(tài)堆棧CGContextSaveGState(context) 入棧 CGContextRestoreGState(context) 彈棧
矩形.png
let context = UIGraphicsGetCurrentContext()
CGContextAddRect(context, CGRect(x: 100, y: 50, width: 100, height: 100))
CGContextAddRect(context, CGRect(x: 150, y: 100, width: 100, height: 100))
//邊框顏色 紅綠藍(lán) 透明度
CGContextSetStrokeColor(context, [0,1,0,1])
//設(shè)置邊框粗細(xì)
CGContextSetLineWidth(context, 4)
// 只畫邊框
// CGContextStrokePath(context)
//只畫填充
// CGContextFillPath(context)
//填充顏色
CGContextSetFillColor(context, [1, 0, 0, 1])
//非零環(huán)繞數(shù)
//Even-Odd 用來判斷填充的內(nèi)部 畫填充或者邊框
根據(jù)奇偶來判斷外部還是內(nèi)部 交叉點(diǎn)為偶數(shù)則是外部 不填充
CGContextDrawPath(context,.EOFillStroke)
繪制圓和圓弧
//給定一個矩形就能確定一個圓 相切原理
CGContextAddEllipseInRect(context, CGRect(x: 100, y: 100, width: 100, height: 200))
//圓點(diǎn) 半徑 起點(diǎn)角度 終點(diǎn)角度 1 代表順時針 電腦反方向認(rèn)為
//繪制橢圓
CGContextAddArc(context, 100, 100, 100,0, CGFloat(M_PI_2), 1)
//注意當(dāng)前點(diǎn)的位置 及上圖最后一個點(diǎn)的位置
//第一個坐標(biāo)表示交叉點(diǎn) 第二個坐標(biāo)是兩點(diǎn)確定一線
//確定兩條直線(有交點(diǎn))然后給半徑就能確定一段弧線
//繪制圓弧
CGContextAddArcToPoint(context, 300, 200, 300, 400, 100)
繪制
//貝茲曲線(貝塞爾曲線)
//第一種 只有一個控制點(diǎn) 還有起始點(diǎn)和終點(diǎn)
//第一個坐標(biāo)是控制點(diǎn) 第二個是終點(diǎn) 起始點(diǎn)是上圖給的
CGContextAddQuadCurveToPoint(context, 350, 200, 400, 300)
//找一個新的起點(diǎn)重新畫
CGContextMoveToPoint(context, 0, 600)
//第二種 有兩個控制點(diǎn) 還有一個終點(diǎn) 起點(diǎn)已給出
CGContextAddCurveToPoint(context, 100, 500, 200, 300, 500, 600)
整體效果圖
圓弧 圓弧 貝茲曲線第一種 貝茲曲線第二種.png