继承UIView,在override funcdrawRect(rect: CGRect)中重写绘制方法
let context=UIGraphicsGetCurrentContext()获取画布
画线
CGContextMoveToPoint(context,100, 100)//移动起始点
CGContextAddLineToPoint(context, 150, 200) //连接到下一个点
CGContextSetRGBStrokeColor(context,1,0.11,0.5,1)//设置线的颜色
CGContextSetLineWidth(context,2)//设置线的宽度
CGContextStrokePath(context)//画出线的轨迹
画出矩形
一:
CGContextAddRect(context,CGRect(x: 100,y: 100, width: 100,height: 100))//设置矩形范围,起始点长宽
CGContextFillPath(context) //画出填充色的矩形色块
CGContextStrokePath(context)//画出矩形线条
二:
CGContextFillRect(context,CGRect(x: 200,y: 30, width: 50,height: 50))//直接画出填充色的矩形色块
CGContextStrokeRect(context, CGRect(x: 100, y: 210, width: 80, height: 100)) //直接画出矩形线条
画圆
一
//第二个参数起为圆心,半径,开始弧度,结束弧度,顺逆时针画(0为顺,1为逆)
CGContextAddArc(context, 100, 400, 100, 0, 7, 0)
CGContextFillPath(context) //实心色块
二
//在固定区域中画椭圆,区域为正方形时画出圆形
CGContextAddEllipseInRect(context, CGRect(x: 100, y: 100, width: 200, height: 300))
CGContextStrokePath(context)
将图片画到画布上
需要定义一个CGImageRef对象 varimage:CGImageRef?
var image:CGImageRef?//定义一个CGImageRef 对象
image=UIImage(named:"imdog.jpg")!.CGImage //用资源文件赋值
CGContextSaveGState(context)//保存画布状态
CGContextTranslateCTM(context, 0, 100)//位移
CGContextScaleCTM(context, 1, -1)//y轴翻转
CGContextDrawImage(context, CGRect(x: 0, y: 0, width: 200, height: 300), image)//在指定区域画出
CGContextRestoreGState(context)//恢复画布状态
手指移动画出轨迹
var path=CGPathCreateMutable();//全局的path存储路径
override functouchesBegan(touches: Set<UITouch>,withEvent event: UIEvent?) {
varp=(touches as NSSet).anyObject()?.locationInView(self);//获取开始的点
CGPathMoveToPoint(path, nil, p!.x, p!.y)//移动开始点
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
var pt=(touches as NSSet).anyObject()?.locationInView(self);//获取经过的点
CGPathAddLineToPoint(path, nil, pt!.x, pt!.y)//将经过的点加入轨迹
setNeedsDisplay()//更新界面(调用drawRect方法)
}
override funcdrawRect(rect: CGRect) {
// Drawing code
letcontext=UIGraphicsGetCurrentContext();
//letpath=CGPathCreateMutable();
//CGPathMoveToPoint(path, nil, 100, 100)
//CGPathAddLineToPoint(path, nil, 100, 300)
CGContextAddPath(context,path)//将轨迹加入画布
CGContextStrokePath(context)//画出轨迹
}