【发布时间】:2015-07-16 02:13:21
【问题描述】:
我正在构建一个演示绘图应用程序。我正在使用 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 的“draw box”会更改已绘制的其他路径的 lineColor:
我了解(某种程度上)为什么会发生这种情况,但无法找到解决此问题的方法。任何建议将不胜感激!
【问题讨论】:
-
“更灵活”对您来说究竟意味着什么?你想要什么额外的功能?
-
我在重绘视图时遇到了真正的问题。当我想改变描边颜色时,整个绘图都会改变颜色。当我尝试删除最后添加的路径时,它不会重绘。我想一般来说,我找不到为不同路径添加不同 CGContext 并将它们全部绘制在 DrawRect 中的好方法
-
完全可以在 -drawRect: 内的单个 CGContext 中绘制多条具有不同笔触颜色的线条。您可能想重新表述您的问题,并包含有关您如何尝试做事的更多详细信息。 (提示:每次调用 -drawRect: 时,您都是从头开始——您不能在上次绘制的内容之上绘制或擦除它。如果您想绘制多个路径或颜色,您需要保留多个
path或lineColor值。) -
感谢您的帮助和提示。我已经用我遇到的主要问题更新了问题
标签: ios swift core-graphics drawrect