【问题标题】:Show UIImageView at a size smaller than its intrinsic size以小于其固有尺寸的尺寸显示 UIImageView
【发布时间】:2015-07-31 01:24:04
【问题描述】:

采用 Autolayout 和 Storyboards 后,我不再以精确的尺寸设计屏幕,所以当我使用图像时,我倾向于使用相当大的图像,这样它在 iPad 上看起来很清晰,但可以按比例缩小以适应较小的 iPhone。我将此图像拖到资产目录中。

当我将图像放入 Storyboard 中的视图控制器时,图像想要成为它的固有尺寸。我只能通过设置特定宽度、与另一个对象成比例的宽度或将其限制在其他两个项目之间来使其显示得更小。

我现在处于项目的另一个点,我需要在代码中添加图像。虽然我为图像的框架设置了特定的高度和宽度,但图像仍然以其固有尺寸出现在屏幕上,而不是我使用它设置的位置:

myImage.frame = CGRect(x: self.view.center.x - 50, y: 100, width: 100, height: 100)

关于我缺少什么的任何想法?谢谢!

【问题讨论】:

  • 设置contentModeScaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent
  • 我确实设置了 myImage.contentMode = UIViewContentMode.ScaleAspectFit / 方面保持固定,但它增长超出了框架的定义宽度和高度...
  • 你应该为这个image view设置约束widthheight

标签: ios swift


【解决方案1】:

我看你想在CenterXmargin top 100 中添加一个imageView。并将图像宽高比保持为 100、100 的正方形。下面的代码将对您有所帮助。

    let imageName = "your image name in resource"
    let imageView = UIImageView(frame: CGRectMake(0, 0, 200, 200))
    imageView.image = UIImage(named: imageName)
    imageView.contentMode = .ScaleAspectFit
    imageView.setTranslatesAutoresizingMaskIntoConstraints(false)

    self.view.addSubview(imageView)

    // add your constraint
    let constTop = NSLayoutConstraint(item: imageView, attribute:.Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 100)
    //        var constLeading = NSLayoutConstraint(item: imageView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: self.view.center.x - 50)

    var constCenterX = NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0);

    var constWidth = NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: 100);
    var constHight = NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: 100);

    imageView.addConstraints([constHight, constWidth])
    self.view.addConstraints([constTop, constCenterX])

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    你需要设置 UIImageView 的contentMode,它实际上是UIView 的一个属性:

    https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/swift/enum/c:@E@UIViewContentMode

    如果您在代码中进行布局,我希望您在正确的位置进行...通过覆盖 layoutSubviews(),如果 需要由外部事件触发,事件在父视图上触发setNeedsLayout()

    如果必须在代码中完成,则需要进行大量握手和配置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-30
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 2021-08-28
      相关资源
      最近更新 更多