【问题标题】:Add annotation to resizable image within scrollview在滚动视图中为可调整大小的图像添加注释
【发布时间】:2026-02-09 14:30:01
【问题描述】:

我有一个滚动视图,我在其中加载了一个可以缩放的图像,并且我可以在其中“导航”。 我正在尝试以编程方式将按钮添加到视图中,例如 MapKit 中使用的 MKAnnotation。 这可能吗?

我使用的方法是scrollViewDidZoom

  func scrollViewDidZoom(scrollView: UIScrollView) {
    centerScrollViewContents()
  }

函数centerScrollViewContents在哪里

func centerScrollViewContents() {
    let boundsSize = scrollView.bounds.size
    var contentFrame = imageView.frame
    if contentFrame.size.width < boundsSize.width {
      contentFrame.origin.x = (boundsSize.width - contentFrame.size.width) / 2
    } else { contentFrame.origin.x = 0 }
    if contentFrame.size.height < boundsSize.height {
      contentFrame.origin.y = (boundsSize.height - contentFrame.size.height) / 2
    } else { contentFrame.origin.y = 0 }

    imageView.frame = contentFrame
  }

我添加了带有UITapGestureRecognizer 实现为的按钮/注释

let posTocco = sender.locationInView(scrollView)
println("\(posTocco), \(scrollView.zoomScale)")

var button = UIButton()
let image = UIImage(named: "arrow.png") as UIImage?
button.frame = CGRectMake(posTocco.x, posTocco.y, 30, 30)
button.setImage(image, forState: .Normal)
scrollView.addSubview(button)

当然,我需要在 tapGesture 函数之外定义按钮/注释,但我不知道如何在图像缩放中移动按钮。

有什么帮助吗?

编辑:

我部分地想出了如何解决这个问题,但是按钮在第一次放大/缩小时会稍微移动。 我创建了一个新变量来存储最新的 zoomValue fattoreScalaCorrentescrollViewDidZoom(scrollView:) 我做了魔法

var newLoc = CGPoint(x: posAssolute.x * scrollView.zoomScale, y: posAssolute.y * scrollView.zoomScale)
button.frame = CGRectMake(newLoc.x, newLoc.y, button.frame.width, button.frame.height)

你知道为什么我的按钮在第一次缩放时会轻微移动吗?

EDIT2: 使用后给出的建议

button.frame = CGRectMake(newLoc.x - button.frame.width/2, newLoc.y - button.frame.height/2, button.frame.width, button.frame.height)

按钮似乎有点移动,我不明白为什么。

【问题讨论】:

  • 阅读您的问题几次。主要问题是什么?您期望的确切行为是什么?你需要静态按钮还是什么?
  • 看最后两张图。第一个是只需点击一个点并添加一个按钮即可生成。第二个是放大和缩小后的相同情况。缩放图像时出现这种奇怪的情况会移动按钮
  • 嗯,CGPointposAssolute怎么获得?
  • 像这样:posAssolute = sender.locationInView(imageView),其中imageView是我的Image的容器
  • 我的回答好运吗?

标签: swift uiscrollview uiimageview uitapgesturerecognizer zooming


【解决方案1】:

尝试替换

button.frame = CGRectMake(newLoc.x, newLoc.y, button.frame.width, button.frame.height)

button.frame = CGRectMake(newLoc.x - button.frame.width/2, newLoc.y - button.frame.height/2, button.frame.width, button.frame.height)

【讨论】: