斯威夫特 - 使用CGContext上用手指画出

问题描述 投票:0回答:2

我试图做一个绘图应用程序。我有一个自定义的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)
}

}

当我运行它,但是,我得到的是一个蓝点,随后我的手指,但没有台词?

我究竟做错了什么?

ios swift uiview cgcontext
2个回答
1
投票

两件事情:

  1. 调用self.setNeedsDisplay不会立即拨打drawRect。它只是设置一个标志,以便将drawRect在不久的将来被调用。既然你设置lastPoint从那之后,currentPoint权,当drawRect被称为lastPoint总是等于currentPoint
  2. drawRect重绘每次调用时整个视图,所以顶多你永远只能看到最近的线路。如果你固定的问题1,你必须按照你的手指,而不是一个点短线。如果你想看到整个线索,你需要点存储在一个数组,它是你的视图的属性,然后画线到所有的点连接在drawRect

1
投票

嗨,我做了一些简单的修改和固定代码,希望它可以帮助别人的未来(代码它的更新的斯威夫特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
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.