首先要创建类继承UIView ,然后把storyboard中的view与前边的类绑定,在类中添加init方法 如下
init(code aDecoder:NSCoder!){
super.init(code:aDecoder)
}
然后在方法 drawRect中添加绘图代码
//绘制直线
override func drawRect(rect:CGRect){
//获取context
var context = UIGraphicsGetCurrentContext();
//移动到点坐标(100,100)
CGContextMoveToPoint(context,100,100)
//添加画线从100,100坐标到100,200坐标
CGContextAddLineToPoint(context,100,200)
//直线的颜色
CGContextSetRGBStrokeColor(context,1,0,1,1) //参数分别为context,红色,蓝色,绿色,透明度
//直线的粗细
CGContextSetLineWidth(context,5)
//开始绘制直线
CGContextStrokePath(context)
}
//绘制矩形
override func drawRect(rect:CGRect){
var context = UIGraphicsGetCurrentContext()
//添加矩形
CGContextAddRect(context,CGRect(x:100,y:100,width:100,height:100))
//设置填充颜色
CGContextSetRGBFillColor(context,1,0,1,1)
//填充颜色
CGContextFillPath(context)
CGcontextSetLineWidth(context,5)//边框的粗细
CGContextSetRGBStrokeColor(context,0,1,1,1)//边框的颜色
//设置边框
CGCotextStrokeRect(context,CGRect(x:100,y:100,width:100,height:100))
}
//绘制圆形
override func drawRect(rect:CGRect){
var context = UIGraphicsGetCurrentContext()
//添加弧形
CGContextAddArc(context,150,300,100,0,3.1415926*2 ,0)
设置填充颜色
CGContextSetRGBFillColor(context,1,0,1,1)
CGConetxtFillPath(context)
CGContextAddArc(context,150,300,100,0,3.1415926*2 ,0)
CGContextSetLineWidth(context,10)
CGContextStrokePath(context)
//椭圆
CGContextAddEllipseInRect(context,CGRect(x:50,y:300,width:200,height:100))
CGContextStrokePath(context)//画图
}
//引用图片
var uiImage:CGImageRef?
override func drawRect(rect:CGRect){
uiImage= UIImage(name:“walle.jpg”).CGImage
var context = UIGraphicsGetCurrentContext()
CGContextSaveState(context)//保存状态
CGContextTranslateCTM(context,10,400) //画布平移
CGContextScaleCTM(context,1,-1)//画布y轴反转(图片默认是反的,所以需要y轴反转)
CGContextDrawImage(context,CGRect(x:0,y:0,width:200,height:200))
CGContextRestoreState(context) //恢复状态
}
简单的画板,记录触摸的动作,随着触摸的轨迹画出线条
var path = CGPathCreateMutable()
override func touchBegan(touch:NSSet!,WithEvent event:UIEvent!){
var p = touch.anyObject().locationInView(self)
CGPathMoveToPoint(path,nil,p.x,p.y)
}
override func touchMoved(touch:NSSet!,withEvent event:UIEvent!){
var p = touch.anyObject().locationInView(self)
CGPathAddLineToPoint(path,nil,p.x,p.y)
setNeedsDisplay() //重新绘制
}
override func drawRect(rect:CGRect){
var context = UIGraphicsGetCurrentContext()
CGContextAddPath(context,path)
CGContextStrokePath(context)
}