在UIScrollView中绘制UIImageView

Joh*_*Doe 14 drawing core-graphics ios swift

我有一个UIImageView内部UIScrollView自动缩小以适应所提供的图像.用户可以像往常一样使用捏合手势进行缩放,并且平移手势被设置为需要两次触摸,因为绘图优先.

在发布时,一切看起来都很棒,但是当我调用我的绘图代码时,会发生以下情况: 在此输入图像描述

如您所见,在drawLineFrom(fromPoint:toPoint:)调用时,UIImageView收缩.之后,图形似乎按预期工作(尽管它在每次触摸时都会跳过线条的第一部分).

我的UIPanGestureRecognizer选择器:

@objc func onOneFingerDrawing(_ sender: UIPanGestureRecognizer) {
    switch sender.state {
    case .began:
        swiped = false

        lastPoint = sender.location(in: drawView.imageView)
    case .changed:
        swiped = true

        let currentPoint = sender.location(in: drawView.imageView)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)

        lastPoint = currentPoint
    case .ended:
        guard drawView.scrollView.frame.contains(sender.location(in: drawView.imageView)) else {
            return
        }

        if let newImage = drawView.imageView.image {
            if history.count > historyIndex + 1 {
                history.removeLast((history.count - 1) - historyIndex)
            }

            history.append(newImage)
            historyIndex = history.count - 1
        }
    case .possible,
         .cancelled,
         .failed:
        return
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的drawLineFrom(fromPoint:toPoint:):

@objc func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
    UIGraphicsBeginImageContextWithOptions(drawView.imageView.frame.size, false, UIScreen.main.scale)
    let context = UIGraphicsGetCurrentContext()
    context?.interpolationQuality = .none

    drawView.imageView.image?.draw(in: CGRect(x: 0, y: 0, width: drawView.imageView.frame.size.width, height: drawView.imageView.frame.size.height))

    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)

    context?.setLineCap(.round)
    context?.setLineWidth(lineWidth)
    context?.setStrokeColor(lineColor)
    context?.setBlendMode(blendMode)

    context?.strokePath()

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    drawView.imageView.image = newImage
}
Run Code Online (Sandbox Code Playgroud)

aja*_*asa 5

滚动视图存在图像约束问题。每当您开始渲染图像时,其帧就会根据内容而变化。因此,您需要向图像视图添加长宽比约束(就像我一样)或任何大小约束。请参阅gif以供参考。

在添加图像视图大小约束之前。

在此处输入图片说明

添加图像视图大小约束后。

在此处输入图片说明


Jer*_*iah 0

该绘图会跳过该行的第一部分,因为您正在使用UIPanGestureRecognizer. 他们的系统在向您发送事件之前首先确定它是平底锅.began。您应该将其交换为通用名称UIGestureRecognizer以使其立即启动。在这种情况下,您需要添加额外的逻辑来检查手指的移动和数量。

至于调整大小,如果没有更多信息,很难说。我也会为 ImageView 的背景着色。第一个问题是,缩小的是整个 imageView 还是只是其中的实际图像。