ios - Swift - 使用CGContext用手指画图

标签 ios swift uiview cgcontext

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

}

但是,当我运行它时,我得到的只是一个蓝点跟随我的手指,但没有线条?

我做错了什么?

最佳答案

您好,我做了一些简单的更改并修复了您的代码,希望它对以后的人有所帮助(针对 Swift 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
            }
        }
    }
}

关于ios - Swift - 使用CGContext用手指画图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30221814/

相关文章:

ios - 获取 UIView 的当前角度/旋转/弧度?

ios - 在 Swift 中,如何使用自动布局为 UIView 设置动画,如页面滑入?

ios - 如何在iOS中以实际尺寸打印pdf

ios - 更新 iOS 11 中的左侧导航项目

文本字段内切换按钮的 IOS UI 测试用例

ios - 保存到 iOS 上的文档目录间歇性工作/失败

ios - CDVNotification插件在iOS中不起作用

ios - 禁用 uibutton 的背景

swift - 如何更新混合类型的 Swift 字典值,尤其是数组

swift 3 : Set Finder label color