【发布时间】:2016-04-18 16:09:04
【问题描述】:
当我想在画布上画一个点时,它不会出现。即使我进行一次触摸,也好像程序没有收到第一个 CGPoint 值。只有当我移动手指时,点值才会出现(例如:(190.0, 375.5), (135, 234), ...)
DV.swift
class DV: UIView {
var lines: [Line] = []
var firstPoint: CGPoint!
var lastPoint: CGPoint!
required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder)!
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
lastPoint = touches.first!.locationInView(self)
}
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 drawRect(rect: CGRect) {
var context = UIGraphicsGetCurrentContext()
CGContextBeginPath(context)
// print("fine") starts at beginning only
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)
CGContextSetLineCap(context, .Round)
CGContextSetLineWidth(context, 5)
CGContextStrokePath(context)
}
}
Line.swift // 我的行初始化器
class Line {
var start: CGPoint
var end: CGPoint
init(start _start: CGPoint, end _end: CGPoint) {
start = _start
end = _end
}
}
【问题讨论】:
-
在更深入地查看您的代码之前:您是否尝试过将
print-statements 添加到您感兴趣的函数中?尤其是在进行自定义图形时,调试和记录输出对于跟踪问题非常重要。 -
在
touchesBegan中放一个断点...程序正在接收你的触摸,只是你没有做任何绘图。您不调用setNeedsDisplay,并且您的绘图代码无论如何都假定完整的线段(不是单点)。 -
是的,当我四处移动手指时,它会打印出我手指所描绘的所有点。但它不会打印出第一个值,或者在这种情况下是点。我的猜测是,它仅在我仅移动手指时才接收值。但我不知道是否应该创建一个额外的变量来表示那个点;或者如果它已经在我没有放入画布的点列表中。