【问题标题】:Alignment of UIImageView within UIScrollViewUIScrollView 中 UIImageView 的对齐方式
【发布时间】:2016-08-21 22:58:05
【问题描述】:

我在很多地方都看到过这个话题,但我不明白为什么我的代码完全不起作用。

我有一张从 -90 到 90 度的人造地平线图像。我想通过一个只显示大约-20到20度的小窗口来查看它。然后我想根据我的机器人倾斜的角度上下移动图像。

我首先将 UIImage 添加到 UIImageView。所有的对齐都是正确的。然后我认为上下移动图像的最简单方法是将 UIImageView 添加到 UIScrollView。现在我不知道如何正确对齐。如果我在滚动视图中拖动,我会看到其中的图像,但一旦我放开它就会回到原来的位置。

这是我的代码。这是我编写的第一个 Swift 代码,所以如果有更好的方法可以做到这一点,我欢迎任何嘲笑(开玩笑,要温柔)

override func viewDidLoad() {
    super.viewDidLoad()

    let imageRect = CGRectMake(self.view.frame.width / 2 - 100, self.view.frame.height / 2, 200, 200)

    self.myImageView = UIImageView.init()
    self.myImageView = UIImageView(frame: imageRect)
    self.myImageView.contentMode = UIViewContentMode.Center
    self.myImageView.clipsToBounds = true
    self.myImageView.image = UIImage.init(named:"horizon")
    //self.view.addSubview(self.image)


    self.myScrollView = UIScrollView(frame: imageRect)
    self.myScrollView.contentSize = CGSize(width: imageRect.width, height: imageRect.height)

    self.myImageView.center = self.myScrollView.center
    self.myScrollView.frame = imageRect
    self.myScrollView.backgroundColor = UIColor.blackColor()
    self.myScrollView.contentOffset = CGPoint(x: 0, y: 0)
    self.myScrollView.addSubview(self.myImageView)
    self.view.addSubview(self.myScrollView)

    /////////


    self.connectionStatusLabel.text = "Disconnected"
    self.connectionStatusLabel.textColor = UIColor.redColor()

    self.textBox.font = UIFont(name: self.textBox.font!.fontName, size: 8)

    // Watch Bluetooth connection
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.connectionChanged(_:)), name: BLEServiceChangedStatusNotification, object: nil)


    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.dataReceived(_:)), name: BLEDataChangedStatusNotification, object: nil)


    // Start the Bluetooth discovery process
    btDiscoverySharedInstance
}

【问题讨论】:

    标签: ios swift uiscrollview uiimageview


    【解决方案1】:

    您必须将 scrollView 的 contentSize 设置为实际图像大小,而不是 imageView 的大小。并将 imageView 的大小也设置为实际图像大小:

    let image = UIImage.init(named:"horizon")
    // Set the imageView's size to the actual image size
    self.myImageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    ...
    ...
    // Set the scrollView's contentSize to the actual image size
    self.myScrollView.contentSize = image.size
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      相关资源
      最近更新 更多