使用UIBezierPath可以创建基于矢量的路径,此类是Core Graphics框架关于路径的封装。使用此类可以定义简单的形状,如椭圆、矩形或者有多个直线和曲线段组成的形状等。
UIBezierPath是CGPathRef数据类型的封装。如果是基于矢量形状的路径,都用直线和曲线去创建。我们使用直线段去创建矩形和多边形,使用曲线去创建圆弧(arc)、圆或者其他复杂的曲线形状。
public typealias CGPathRef = CGPath
先看看其所提供的创建方法:
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 radius
public 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)
?待续