使用Swift 5在UIView中绘制签名

时间:2019-04-29 11:24:54

标签: ios swift

我有一个UIView,我尝试在上面签名。 该功能可行,但问题是我的绘图从光标下方的5厘米处开始,我不知道为什么。 这是我的错误的gif文件:

enter image description here

这是我的小项目:DrawSignature

这是我的绘图代码:

struct Line {
    let strokeWidth: Float
    let color: UIColor
    var points: [CGPoint]
}

class Canvas: UIView {

    // public function
    fileprivate var strokeColor = UIColor.black
    fileprivate var strokeWidth: Float = 1

    func setStrokeWidth(width: Float) {
        self.strokeWidth = width
    }

    func setStrokeColor(color: UIColor) {
        self.strokeColor = color
    }

    func undo() {
        _ = lines.popLast()
        setNeedsDisplay()
    }

    func clear() {
        lines.removeAll()
        setNeedsDisplay()
    }

    fileprivate var lines = [Line]()

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        guard let context = UIGraphicsGetCurrentContext() else { return }

        lines.forEach { (line) in
            context.setStrokeColor(line.color.cgColor)
            context.setLineWidth(CGFloat(line.strokeWidth))
            context.setLineCap(.round)
            for (i, p) in line.points.enumerated() {
                if i == 0 {
                    context.move(to: p)
                } else {
                    context.addLine(to: p)
                }
            }
            context.strokePath()
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        lines.append(Line.init(strokeWidth: strokeWidth, color: strokeColor, points: []))
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let point = touches.first?.location(in: nil) else { return }
        guard var lastLine = lines.popLast() else { return }
        lastLine.points.append(point)
        lines.append(lastLine)
        setNeedsDisplay()
    }
}

这是我的ViewController:

class ViewController: UIViewController {

    // Interface Links
    @IBOutlet weak var signatureView: Canvas!

    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()

        signatureView.setStrokeColor(color: .black)
    }

    func setupViews(){

        signatureView.layer.borderWidth = 0.5
        signatureView.layer.borderColor = UIColor.black.cgColor
        signatureView.layer.cornerRadius = 10
    }

    @IBAction func clearBtnTapped(_ sender: UIButton) {

        signatureView.clear()
    }
}

1 个答案:

答案 0 :(得分:1)

我解决了。问题出在这一行:

guard let point = touches.first?.location(in: nil) else { return }

修正为:

guard let point = touches.first?.location(in: self) else { return }