本文首发在我的个人博客ghui.me欢迎指教
使用UIKit实现自定义绘图主要是通过UIBezierPath
这个类,它可以创建基于矢量的路径,和sketch
及ps
中的路径是同一个概念.对应Android中的Path
这个类,实现的功能是一样的,但还是有些地方和Android中的使用不太一样,主要是因为iOS中没有Canvas
及Paint
这两个类,第一次使用时有些不习惯,这里总结一下如何使用UIBezierPath
绘制常见的图形.
最终效果大致如下:
![](https://img.haomeiwen.com/i632614/07926922d8abd6df.png)
1. 直线
let pathLine = UIBezierPath()
UIColor.blueColor().setStroke() //设置线条的颜色
pathLine.lineWidth = 5
pathLine.moveToPoint(CGPoint(x: 100, y: y))
pathLine.addLineToPoint(CGPoint(x: 300, y: y))
pathLine.lineCapStyle = .Round //线条结束点的形状
pathLine.stroke() // 画线条
2. 矩形
最简单的方式是通过UIRectFill
(只能绘制实心的矩形)
UIColor.blackColor().setFill()
UIRectFill(CGRect(x: 100, y: y, width: 150, height: 50))
通过UIBezierPath
可以控制是否实心及边框的颜色:
let pathRect = UIBezierPath(rect: CGRect(x: 100, y: y, width: 50, height: 50))
pathRect.lineWidth = 5
UIColor.redColor().setStroke() //线条颜色
pathRect.lineJoinStyle = .Round //连接点形状
pathRect.stroke() //绘制边框
UIColor.blueColor().setFill() //填充颜色
pathRect.fill() //绘制填充内容
绘制四个角都是圆角的矩形:
let pathRect = UIBezierPath(roundedRect: CGRect(x: 10, y: y + 50, width: 100, height: 40), cornerRadius: 8.0)
UIColor.blackColor().setFill()
pathRect.fill()
绘制部分角是圆角的矩形:
let corners = UIRectCorner.TopLeft.union(UIRectCorner.BottomLeft)
pathRect = UIBezierPath(roundedRect: CGRect(x: 10, y: y + 150, width: 100, height: 40) ,byRoundingCorners: corners, cornerRadii: CGSize(width: 10, height: 10))
pathRect.stroke()
3. 圆
let pathCircle = UIBezierPath(ovalInRect: CGRect(x: 100, y: y, width: 50, height: 50))
UIColor.greenColor().setFill()
pathCircle.fill()
pathCircle.lineWidth = 5
UIColor.redColor().setStroke()
pathCircle.stroke()
具体是绘制正圆还是椭圆直接通过上面的 width
与height
来控制,两者相等绘制出来就是正圆,否则就是椭圆.
4. 多边形
多边形的绘制主要依赖moveToPoint
与addLineToPoint
这两个方法,通过不同的组合画出不同的图形
let pathPg = UIBezierPath()
pathPg.moveToPoint(CGPoint(x: 100, y: y))
pathPg.addLineToPoint(CGPoint(x: 130, y: y + 120))
pathPg.addLineToPoint(CGPoint(x: 200, y: y + 30))
pathPg.addLineToPoint(CGPoint(x: 150, y: y + 40))
UIColor.cyanColor().setFill()
pathPg.fill()
5. 圆弧
普通的弧线
UIColor.blackColor().setStroke()
let pathArc = UIBezierPath(arcCenter: CGPoint(x: 120, y: y), radius: 40, startAngle: 0.0, endAngle: CGFloat(120 * M_PI / 180) , clockwise: true)
pathArc.lineWidth = 3
pathArc.stroke()
或者
let pathArc2 = UIBezierPath()
pathArc2.addArcWithCenter(CGPoint(x: 240, y: y), radius: 40, startAngle: 0.0, endAngle: CGFloat(160 * M_PI / 180), clockwise: true)
pathArc2.lineWidth = 3
pathArc2.stroke()
如果要想绘制扇形,只需要在上面的基础上再画一条到圆弧中心点的线即可.
6. 曲线
UIBezierPath
提供了两种绘制曲线的方法:addQuadCurveToPoint
及addCurveToPoint
, 前者是绘制二次贝塞尔曲线
后者绘制三次贝塞尔曲线
,一般这两种就可以满足绘制曲线的需求的,所以UIBezierPath
也没提供更高阶的曲线绘制的方法:
二次贝塞尔曲线(一个控制点P1)
![](https://img.haomeiwen.com/i632614/e97eb28a2dfb91f1.jpg)
网友评论