Swift-使用CGContext用手指绘制 [英] Swift - Using CGContext to draw with finger
问题描述
我正在尝试制作绘图应用。我有一个自定义UIView:
I'm trying to make a drawing app. I have a single custom 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)
}
}
但是,当我运行它时,我得到的只是一个蓝色的点,它紧跟着我的手指,但没有线条?
When I run it, however, all I get is a blue dot that follows my finger, but no lines?
我在做什么错了?
推荐答案
两件事:
-
调用
self.setNe edsDisplay
不会立即调用drawRect
。它只是设置一个标志,以便在不久的将来调用drawRect
。由于在此之后立即将lastPoint
设置为currentPoint
,因此当drawRect
称为lastPoint
始终等于currentPoint
。
Calling
self.setNeedsDisplay
doesn't immediately calldrawRect
. It just sets a flag so thatdrawRect
will be called in the near future. Since you setlastPoint
tocurrentPoint
right after that, whendrawRect
is calledlastPoint
is always equal tocurrentPoint
.
drawRect
每次调用时都会重绘整个视图,因此最多您只会看到最新的一行。如果您解决了问题1,则手指后会有短线而不是点。如果要查看整个踪迹,则需要将点存储在视图属性的数组中,然后绘制线以连接 drawRect $ c中的所有点$ c>。
drawRect
redraws the entire view every time it is called, so at most you'd only ever see the most recent line. If you fixed problem 1, you'd have a short line following your finger instead of a dot. If you want to see the whole trail, you'll need to store the points in an array that is a property of your view, and then draw lines to connect all of the points in drawRect
.
这篇关于Swift-使用CGContext用手指绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!