UIBezierPath

来源:互联网 发布:聚合tv软件 编辑:程序博客网 时间:2024/05/19 02:21

使用UIBezierPath可以创建基于矢量的路径,此类是Core Graphics框架关于路径的封装。使用此类可以定义简单的形状,如椭圆、矩形或者有多个直线和曲线段组成的形状等。

UIBezierPath是CGPathRef数据类型的封装。如果是基于矢量形状的路径,都用直线和曲线去创建。我们使用直线段去创建矩形和多边形,使用曲线去创建圆弧(arc)、圆或者其他复杂的曲线形状。

public typealias CGPathRef = CGPath

使用UIBezierPath画图的步骤:

  • 创建一个UIBezierPath对象
  • 设置初始起点 调用方法 public func moveToPoint(point: CGPoint)
  • 添加线或者曲线去定义一个或者多个子路径
  • 改变UIBezierPath对象跟绘图相关的属性画笔的属性、填充样式等

UIBezierPath的创建方法

先看看其所提供的创建方法:

public convenience init(rect: CGRect)public convenience init(ovalInRect rect: CGRect)public convenience init(roundedRect rect: CGRect, cornerRadius: CGFloat) // rounds all corners with the same horizontal and vertical radiuspublic convenience init(roundedRect rect: CGRect, byRoundingCorners corners: UIRectCorner, cornerRadii: CGSize)public convenience init(arcCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool)

以下对这些方法一一说明:

  • 绘制矩形
public convenience init(rect: CGRect)
  • 绘制椭圆
public convenience init(ovalInRect rect: CGRect)
  • 绘制圆角矩形
public convenience init(roundedRect rect: CGRect, cornerRadius: CGFloat)
  • 绘制可以指定圆角的矩形
public convenience init(roundedRect rect: CGRect, byRoundingCorners corners: UIRectCorner, cornerRadii: CGSize)

示例:

let corner = UIRectCorner(rawValue: ***0xB***)let rect1 = CGRectMake(20, 20, 100, 100)let path = UIBezierPath(roundedRect: rect1, byRoundingCorners: corner, cornerRadii: CGSizeMake(30, 10))path.fill()

其中0xB是设置矩形具体哪一个角是圆角的示例,如果定义一个矩形,从左上角开始定义未1号,顺时针分别将其他几个角标识未2,3,4,
这里写图片描述
0xB对应的二进制是:1011(8-4-2-1)分别对应1-4-2-3,所以就看到上面的图形

UIRectCorner这个结构体是怎么定义的呢?参考如下:

public struct UIRectCorner : OptionSetType {public init(rawValue: UInt)public static var TopLeft: UIRectCorner { get }public static var TopRight: UIRectCorner { get }public static var BottomLeft: UIRectCorner { get }public static var BottomRight: UIRectCorner { get }public static var AllCorners: UIRectCorner { get }}

其中方法内部的几个变量定义如下:

rect:*The rectangle that defines the basic shape of the path.*corners:*A bitmask value that identifies the corners that you want rounded. You can use this parameter to round only a subset of the corners of the rectangle.*cornerRadii:*The radius of each corner oval. Values larger than half the rectangle’s width or height are clamped appropriately to half the width or height.*
  • 绘制扇形
public convenience init(arcCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool)

?待续

0 0
原创粉丝点击