在缩放的图像上绘图

时间:2019-03-05 11:21:40

标签: ios swift uipangesturerecognizer

我有一个带有图像视图的滚动视图。用户可以捏捏以正确放大和缩小。现在,我尝试在图像上绘图,但是遇到一个问题:如果缩放并尝试在图像的可见部分上绘图,图像将缩小并恢复为完全可见。

仅当我开始在缩放的图像上绘制时,才会出现此问题。如果我先在图像上绘制,然后缩放并尝试绘制,则一切看起来都很好。

下面是我的代码。

scrollView.panGestureRecognizer.minimumNumberOfTouches = 2
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:)))
scrollView.addGestureRecognizer(panGestureRecognizer)

然后选择器

@objc func didPan(_ sender: UIPanGestureRecognizer) {
    switch sender.state {
    case .began:
        lastPoint = sender.location(in: imageView)
    case .changed:
        let currentPoint = sender.location(in: imageView)
        imageView.image = imageView.draw(from: lastPoint, to: currentPoint)
        lastPoint = currentPoint
    case .ended:
        imageView.image = imageView.draw(from: lastPoint, to: lastPoint)
    default:
        print("Don't care")
    }
}

最后我要画的东西

extension UIImageView {
    func draw(from: CGPoint, to: CGPoint) -> UIImage? {
        if let image = image {
            UIGraphicsBeginImageContext(image.size)
            let context = UIGraphicsGetCurrentContext()
            image.draw(in: CGRect(origin: .zero, size: image.size))

            let scaleWidth = image.size.width / bounds.size.width
            let scaleHeight = image.size.height / bounds.size.height

            let brushWidth: CGFloat = 50
            let fromPoint = CGPoint(x: from.x * scaleWidth, y: from.y * scaleHeight)
            let toPoint = CGPoint(x: to.x * scaleWidth, y: to.y * scaleHeight)

            context?.move(to: fromPoint)
            context?.addLine(to: toPoint)
            context?.setLineCap(.round)
            context?.setLineWidth(scaleWidth * brushWidth)
            context?.setFillColor(UIColor.black.cgColor)
            context?.setBlendMode(.normal)
            context?.strokePath()

            let result = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return result
        }
        return nil
    }
}

0 个答案:

没有答案