swift - 在 ScrollView 中向可调整大小的图像添加注释

标签 swift uiscrollview uiimageview uitapgesturerecognizer zooming

我有一个 ScrollView ,我在其中加载了一个可以缩放的图像,并且可以在其中“导航”。 我正在尝试以编程方式将按钮添加到 View 中,例如 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 fattoreScalaCorrente 并在 scrollViewDidZoom(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)

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

Before zoom in/out

After zoom in/out

编辑 2: 在给出建议后使用

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

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

enter image description here enter image description here

最佳答案

尝试替换

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)

关于swift - 在 ScrollView 中向可调整大小的图像添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32183350/

相关文章:

ios - 如何在 iPhone X 上滚动时隐藏状态栏上的内容

ios - 如何检测 UIScrollView 何时在 Swift 中完成滚动

ios - iPad 应用程序 - 如何使用手指滑动终止服务器调用

ios - 如何在图像上画线/绘画?

ios - UIButton 框架不随图像调整大小

ios - 如何停止在 tableview 单元格中显示为黑色的透明 PNG 图像

swift - 在 Swift 中定义函数时,如果 return 声明在括号内会发生什么?

ios - 无法在 swift 中重载 viewDidLoad() 中的函数

ios - 如何在 iOS 上处理带有 .m3u8 文件的 CloudFront 签名 Cookie?

swift - UITextField 打开时被键盘部分隐藏