import UIKit
class CustomView: UIView {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
drawGrid()
// 1.连接上下文
let context = UIGraphicsGetCurrentContext()
// 2.绘制矩形
CGContextAddRect(context, CGRect(x: 100, y: 100, width: 100, height: 200))
CGContextAddRect(context, CGRect(x: 150, y: 200, width: 100, height: 200))
// 3.绘制椭圆(圆形,正方矩形)
CGContextAddEllipseInRect(context, CGRect(x: 0, y: 0, width: 100, height: 200))
CGContextAddEllipseInRect(context, CGRect(x: 200, y: 200, width: 100, height: 100))
// 设置边框色
CGContextSetStrokeColor(context, [1, 0, 0, 1])
// 设置填充色
CGContextSetFillColor(context, [1, 1, 0, 1])
// 只绘制边框
CGContextStrokePath(context)
// 只填充
CGContextFillPath(context)
//5. 绘制
CGContextStrokePath(context)
如果想要有边框又有填充,则需要用下面的函数
CGContextDrawPath(context, .FillStroke)
注意:有EO的填充是不同的
//非零环绕数 (每个图都是向左或者向右绘制的,只要有交点非零就执行)
//EO:Even-Odd 奇偶数,根据交点奇数,偶数填充颜色 (奇数个交点填充,偶数不填充)
CGContextDrawPath(context, .EOFillStroke)
}
func drawGrid() {
//1. 获取上下文
let context = UIGraphicsGetCurrentContext()
var y: CGFloat = 50
while y < self.bounds.size.height {
//2. 开始,设置绘制起点
CGContextMoveToPoint(context, 0, y)
//3. 往上下文上添加图形
CGContextAddLineToPoint(context, self.bounds.size.width, y)
y += 50
}
var x: CGFloat = 50
while x < self.bounds.size.width {
//2. 开始,设置绘制起点
CGContextMoveToPoint(context, x, 0)
//3. 往上下文上添加图形
CGContextAddLineToPoint(context, x, self.bounds.size.height)
x += 50
}
//保存当前的上下文状态
CGContextSaveGState(context)
//4. 设置颜色、样式、尺寸
CGContextSetLineWidth(context, 1)
CGContextSetLineDash(context, 0, [4, 10], 2)
// CGContextSetLineCap(context, .Round)
// CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
CGContextSetStrokeColor(context, [0, 1, 0, 1])
//5. 绘制
CGContextStrokePath(context)
//恢复到上次保存时的状态
CGContextRestoreGState(context)
}
}
Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png