显示比UIImageView本身尺寸小的UIImageView

3

我已经采用了Autolayout和Storyboards,不再以精确的尺寸设计屏幕,因此当我使用图片时,我倾向于使用较大的图片,以便在iPad上看起来清晰,并可缩小到较小的iPhone上。我将这个图像拖入资产目录。

当我把图片放到Storyboard中的视图控制器中时,这个图片希望成为它的本质大小。我只能通过设置特定的宽度、与另一个对象的比例宽度或将其约束在两个其他项之间来使它显示得更小。

现在我需要在代码中添加图片。尽管我为图片的框架设置了特定的高度和宽度,但是图片仍然以其本质大小出现在屏幕上,而不是我使用以下语句进行设置:

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

有什么想法我可能漏掉了吗?谢谢!

1
contentMode设置为ScaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent - Long Pham
我设置了myImage.contentMode = UIViewContentMode.ScaleAspectFit / 它的宽高比保持不变,但它会超出框架定义的宽度和高度... - RanLearns
你应该为这个“图像视图”设置“宽度”和“高度”的约束。 - Long Pham
2个回答

1
我发现您想在中心位置添加一个imageView,并且离顶部有100的间距。图片应该保持100x100的正方形比例。下面的代码可以帮助您实现此目标。
    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()
如果必须在代码中完成此操作,则需要进行大量的握手和配置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接