在scrollview中为可调整大小的图像添加注释

时间:2015-08-24 13:18:15

标签: swift uiscrollview uiimageview uitapgesturerecognizer image-zoom

我有一个滚动视图,我在其中加载了一个可以缩放的图像以及我可以在哪里导航"。 我试图以编程方式将按钮添加到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

EDIT2: 在使用

给出建议之后
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

1 个答案:

答案 0 :(得分: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)