我正在创建一个绘图应用程序。一开始我的画很流畅。当我长时间绘制一堆圆圈时,我的绘图开始变得前卫。也许这是数组不能处理太多点的事实吗?
DV.swift:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
lastPoint = touches.first!.locationInView(self)
self.setNeedsDisplay()
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
var newPoint = touches.first!.locationInView(self)
lines.append(Line(start: lastPoint, end: newPoint))
lastPoint = newPoint
self.setNeedsDisplay()
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
var veryFirstPoint = touches.first!.locationInView(self)
lines.append(Line(start: lastPoint, end:veryFirstPoint))
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
var context = UIGraphicsGetCurrentContext()
CGContextBeginPath(context)
for line in lines {
CGContextMoveToPoint(context,line.start.x , line.start.y)
CGContextAddLineToPoint(context, line.end.x, line.end.y)
}
CGContextSetRGBFillColor(context, 0, 0, 0, 1)
CGContextSetLineWidth(context, 5)
CGContextStrokePath(context)
}
在我的iPad mini 4上测试的示例:左侧是绘制了一堆循环后的锯齿状数字。右边是我画的前几个数字,它们很平滑。
你说的对。每次添加新的“行”时(即每次触摸后),CPU都会重绘许多路径。您拥有的行数越多,处理器的处理量就会越来越大。一种解决方案是仅重绘视图的“脏”部分。您可以使用setNeedsDisplayInRect(rect:CGRect)
代替来做到这一点setNeedsDisplay()
。例如,您可以添加扩展名:
extension CGRect{
static func rectWithTwoPoints(p1:CGPoint,p2:CGPoint) -> CGRect
{
return CGRectMake(min(p1.x, p2.x),min(p1.y, p2.y),fabs(p1.x - p2.x),fabs(p1.y - p2.y));
}
}
这将给我一个包含任何两点的信息。现在在您中touchesMoved:
,touchesEnded:
我们可以这样打电话setNeedsDisplayInRect:
:
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let newPoint = touches.first!.locationInView(self)
lines.append(Line(start: lastPoint, end: newPoint))
lastPoint = newPoint
self.setNeedsDisplayInRect(CGRectInset(CGRect.rectWithTwoPoints((lines.last?.start)!, p2: (lines.last?.end)!),-10.0,-10.0)) //would be better to not force unwrap and use magic numbers, but you get the idea
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let veryFirstPoint = touches.first!.locationInView(self)
lines.append(Line(start: lastPoint, end:veryFirstPoint))
self.setNeedsDisplayInRect(CGRectInset(CGRect.rectWithTwoPoints((lines.last?.start)!, p2: (lines.last?.end)!),-10.0,-10.0))
}
使用CGRectInset
扩展我们的rect有点,因为我们有一个路径宽度,如果我们仅重绘rectWithTwoPoints返回的rect,则会考虑在内。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句