使用CGPathCreateCopyByStrokingPath 创建一个新路径,该路径以您指定的偏移量勾勒出当前路径(偏移量是lineWidth 的一半)。然后描边那条新路径。
更新
这是一个函数,它接受一条线段(作为一对点)和一个偏移量,并返回一条与原始线段平行并偏离原始线段的新线段。
func lineSegment(segment: (CGPoint, CGPoint), offsetBy offset: CGFloat) -> (CGPoint, CGPoint) {
let p0 = segment.0
let p1 = segment.1
// Compute (dx, dy) as a vector in the direction from p0 to p1, with length `offset`.
var dx = p1.x - p0.x
var dy = p1.y - p0.y
let length = hypot(dx, dy)
dx *= offset / length
dy *= offset / length
// Rotate the vector one quarter turn in the direction from the x axis to the y axis, so it's perpendicular to the line segment from p0 to p1.
(dx, dy) = (-dy, dx)
let p0Out = CGPointMake(p0.x + dx, p0.y + dy)
let p1Out = CGPointMake(p1.x + dx, p1.y + dy)
return (p0Out, p1Out)
}
这是一个使用它的游乐场示例:
func stroke(segment: (CGPoint, CGPoint), lineWidth: CGFloat, color: UIColor) {
let path = UIBezierPath()
path.moveToPoint(segment.0)
path.addLineToPoint(segment.1)
path.lineWidth = lineWidth
color.setStroke()
path.stroke()
}
let mainSegment = (CGPointMake(20, 10), CGPointMake(50, 30))
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 60), true, 2)
UIColor.whiteColor().setFill(); UIRectFill(.infinite)
stroke(mainSegment, lineWidth: 1, color: .blackColor())
stroke(lineSegment(mainSegment, offsetBy: 10), lineWidth: 2, color: .redColor())
stroke(lineSegment(mainSegment, offsetBy: -10), lineWidth: 2, color: .blueColor())
let image = UIGraphicsGetImageFromCurrentImageContext()
XCPlaygroundPage.currentPage.captureValue(image, withIdentifier: "image")
结果: