4.Swift 自定义View
绘制线条
import UIKit
,在UIKit中有一个UIGraphics.h,这个类中存在func UIGraphicsGetCurrentContext() -> CGContext
方法为我们提供CGContext的实例
设置点的位置
CGContext.CGContextMoveToPoint(c: CGContext?, _ x: CGFloat, _ y: CGFloat)
添加一条直线
CGContext.CGContextAddLineToPoint(c: CGContext?, _ x: CGFloat, _ y: CGFloat)
通过RGB设置边的颜色
CGContext.CGContextSetRGBStrokeColor(c: CGContext?, _ red: CGFloat, _ green: CGFloat, _ blue: CGFloat, _ alpha: CGFloat)
设置线宽度
CGContext.CGContextSetLineWidth(c: CGContext?, _ width: CGFloat)
绘制边的路径
CGContext.CGContextStrokePath(c: CGContext?)
class DrawLinesView: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// 获得CGContext,相当于画笔的角色
let paint:CGContext = UIGraphicsGetCurrentContext()!
// 设置点的位置
CGContextMoveToPoint(paint, 200, 200)
// 添加一条直线段从当前的点,指向到(x,y)
CGContextAddLineToPoint(paint, 300, 200)
CGContextMoveToPoint(paint, 250, 150)
CGContextAddLineToPoint(paint, 250, 250)
CGContextMoveToPoint(paint, 200, 150)
CGContextAddLineToPoint(paint, 300, 150)
CGContextMoveToPoint(paint, 200, 250)
CGContextAddLineToPoint(paint, 300, 250)
CGContextMoveToPoint(paint, 200, 250)
CGContextAddLineToPoint(paint, 300, 250)
CGContextMoveToPoint(paint, 280, 235)
CGContextAddLineToPoint