swift 绘图

继承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)//画出轨迹

       

   }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值