Swift-使用CGContext用手指绘制 [英] Swift - Using CGContext to draw with finger

查看:294
本文介绍了Swift-使用CGContext用手指绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作绘图应用。我有一个自定义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?

我在做什么错了?

推荐答案

两件事:


  1. 调用 self.setNe edsDisplay 不会立即调用 drawRect 。它只是设置一个标志,以便在不久的将来调用 drawRect 。由于在此之后立即将 lastPoint 设置为 currentPoint ,因此当 drawRect 称为 lastPoint 始终等于 currentPoint

  1. Calling self.setNeedsDisplay doesn't immediately call drawRect. It just sets a flag so that drawRect will be called in the near future. Since you set lastPoint to currentPoint right after that, when drawRect is called lastPoint is always equal to currentPoint.

drawRect 每次调用时都会重绘整个视图,因此最多您只会看到最新的一行。如果您解决了问题1,则手指后会有短线而不是点。如果要查看整个踪迹,则需要将点存储在视图属性的数组中,然后绘制线以连接 drawRect

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆