IOS绘图API绘制直线几何图形

首先要创建类继承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)


}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值