我试图做一个绘图应用程序。我有一个自定义的UIView:
class DrawView: UIView {
var touch : UITouch!
var lastPoint : CGPoint!
var currentPoint : CGPoint!
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
touch = touches.first as! UITouch
lastPoint = touch.locationInView(self)
println(lastPoint)
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
touch = touches.first as! UITouch
currentPoint = touch.locationInView(self)
self.setNeedsDisplay()
lastPoint = currentPoint
}
override func drawRect(rect: CGRect) {
var context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 5)
CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor)
CGContextSetLineCap(context, kCGLineCapRound)
CGContextBeginPath(context)
if lastPoint != nil {
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y)
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y)
}
CGContextStrokePath(context)
}
}
当我运行它,但是,我得到的是一个蓝点,随后我的手指,但没有台词?
我究竟做错了什么?
两件事情:
self.setNeedsDisplay
不会立即拨打drawRect
。它只是设置一个标志,以便将drawRect
在不久的将来被调用。既然你设置lastPoint
从那之后,currentPoint
权,当drawRect
被称为lastPoint
总是等于currentPoint
。drawRect
重绘每次调用时整个视图,所以顶多你永远只能看到最近的线路。如果你固定的问题1,你必须按照你的手指,而不是一个点短线。如果你想看到整个线索,你需要点存储在一个数组,它是你的视图的属性,然后画线到所有的点连接在drawRect
。嗨,我做了一些简单的修改和固定代码,希望它可以帮助别人的未来(代码它的更新的斯威夫特3):
class DrawView: UIView {
var touch : UITouch!
var lineArray : [[CGPoint]] = [[CGPoint]()]
var index = -1
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
touch = touches.first! as UITouch
let lastPoint = touch.location(in: self)
index += 1
lineArray.append([CGPoint]())
lineArray[index].append(lastPoint)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
touch = touches.first! as UITouch
let currentPoint = touch.location(in: self)
self.setNeedsDisplay()
lineArray[index].append(currentPoint)
}
override func draw(_ rect: CGRect) {
if(index >= 0){
let context = UIGraphicsGetCurrentContext()
context!.setLineWidth(5)
context!.setStrokeColor((UIColor(red:0.00, green:0.38, blue:0.83, alpha:1.0)).cgColor)
context!.setLineCap(.round)
var j = 0
while( j <= index ){
context!.beginPath()
var i = 0
context?.move(to: lineArray[j][0])
while(i < lineArray[j].count){
context?.addLine(to: lineArray[j][i])
i += 1
}
context!.strokePath()
j += 1
}
}
}
}