我正在构建一个演示绘图应用程序。我正在使用 touchesMoved:withEvent 来收集我的积分并将它们添加到 CGMutablePathRef 。要描边路径,我重写DrawRect,添加上下文的路径并描绘路径:
override func drawRect(rect: CGRect) {
self.backgroundColor?.set()
UIRectFill(rect)
let context : CGContextRef = UIGraphicsGetCurrentContext()
for line in pathArray {
CGContextAddPath(context, line.structPath)
CGContextSetLineWidth(context, line.structLineWidth)
CGContextSetStrokeColorWithColor(context, line.structLineColor.CGColor)
CGContextSetAlpha(context, lineOpacity)
}
CGContextSetLineCap(context, kCGLineCapRound)
CGContextStrokePath(context)
self.empty = false
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first as UITouch! {
previousPoint = touch.previousLocationInView(self)
previousPreviousPoint = touch.previousLocationInView(self)
currentPoint = touch.locationInView(self)
}
self.touchesMoved(touches, withEvent: event)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first as UITouch! {
previousPreviousPoint = previousPoint
previousPoint = touch.previousLocationInView(self)
currentPoint = touch.locationInView(self)
let mid1 : CGPoint = getMidPoint(previousPoint, p2: previousPreviousPoint)
let mid2 : CGPoint = getMidPoint(currentPoint, p2: previousPoint)
let subpath : CGMutablePathRef = CGPathCreateMutable()
CGPathMoveToPoint(subpath, nil, mid1.x, mid1.y)
CGPathAddQuadCurveToPoint(subpath, nil, previousPoint.x, previousPoint.y, mid2.x, mid2.y)
let bounds : CGRect = CGPathGetBoundingBox(subpath)
let drawBox : CGRect = CGRectInset(bounds, -2.0 * lineWidth, -2.0 * lineWidth)
let newLine = line(newPath: subpath)
pathArray.append(newLine)
self.setNeedsDisplayInRect(drawBox)
}
}
上面的代码按预期工作,除了我看到意外的结果。获取bandbox并设置CGRectInset的“绘图框”会更改已绘制的其他路径的lineColor:
我理解(有点)为什么会这样,但无法找到解决这个问题的方法。任何建议都将非常感谢!
答案 0 :(得分:2)
您想分别描边每条路径,如下所示:
override func drawRect(rect: CGRect) {
let context : CGContextRef = UIGraphicsGetCurrentContext()
// Set parameters in the context that are the same for all lines
CGContextSetLineCap(context, kCGLineCapRound)
CGContextSetAlpha(context, lineOpacity)
for line in pathArray {
// Set parameters in the context that are specific to this line
CGContextSetLineWidth(context, line.structLineWidth)
CGContextSetStrokeColorWithColor(context, line.structLineColor.CGColor)
// Add the line's path to the context's current path:
CGContextAddPath(context, line.structPath)
// And stroke it.
CGContextStrokePath(context)
// (This has the side effect of clearing the context's current path.)
}
}
CGContext跟踪当前路径。可以将其视为您无法直接访问的CGMutablePath
。您可以通过调用CGContextAddPath
或其他许多函数来影响它。
CGContext的当前路径实际上是不可见的,除非您通过调用类似CGContextStrokePath
的函数告诉上下文绘制它。那时,上下文使用当前路径和上下文中的其他值(笔触颜色,alpha,线宽等)来确定要绘制的内容并绘制它。
您的代码将每行的路径添加到当前路径中,因此您最终得到包含多个断开连接的子路径的当前路径。然后在最后调用CGContextStrokePath
一次,并使用您最近设置的参数值绘制所有这些子路径。所以你只看到了最后一行的宽度和颜色。