gpt4 book ai didi

ios - 在 UIScrollView 中绘制 UIImageView

转载 作者:IT王子 更新时间:2023-10-29 05:24:19 27 4
gpt4 key购买 nike

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

启动时,一切看起来都很棒,但是当我调用我的绘图代码时,会发生这种情况:enter image description here

如您所见,调用 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
}
}

和我的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
}

最佳答案

ScrollView 的图像约束存在问题。每当您开始渲染图像时,它的框架就会根据内容发生变化。因此,您需要向 ImageView 添加宽高比约束(就像我所做的那样)或任何大小约束。查看 gif 以供引用。

Before add image view size constraint.

enter image description here

After adding image view size constraint.

enter image description here

关于ios - 在 UIScrollView 中绘制 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49646631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com