Ios 以小于其固有大小的大小显示UIImageView
由于采用了自动布局和情节串连板,我不再设计精确尺寸的屏幕,因此当我使用图像时,我倾向于使用相当大的图像,以便在iPad上看起来清晰,但在较小的iPhone上可以缩小。我将此图像拖到资源目录中 当我将图像放入情节提要中的视图控制器时,图像希望成为其固有大小。我只能通过设置一个特定的宽度,与另一个对象的宽度成比例,或者通过将它限制在两个其他项目之间,使它显示得更小 我现在正处于项目的另一个阶段,需要在代码中添加图像。虽然我正在为图像的边框设置特定的高度和宽度,但图像仍以其固有大小显示在屏幕上,而不是我使用以下方法设置的位置:Ios 以小于其固有大小的大小显示UIImageView,ios,swift,Ios,Swift,由于采用了自动布局和情节串连板,我不再设计精确尺寸的屏幕,因此当我使用图像时,我倾向于使用相当大的图像,以便在iPad上看起来清晰,但在较小的iPhone上可以缩小。我将此图像拖到资源目录中 当我将图像放入情节提要中的视图控制器时,图像希望成为其固有大小。我只能通过设置一个特定的宽度,与另一个对象的宽度成比例,或者通过将它限制在两个其他项目之间,使它显示得更小 我现在正处于项目的另一个阶段,需要在代码中添加图像。虽然我正在为图像的边框设置特定的高度和宽度,但图像仍以其固有大小显示在屏幕上,而不是
myImage.frame = CGRect(x: self.view.center.x - 50, y: 100, width: 100, height: 100)
你知道我遗漏了什么吗?谢谢 您需要设置UIImageView的
contentMode
,它实际上是UIView
的一个属性:
如果你在代码中使用布局,我希望你在正确的地方使用它。。。通过重写layoutSubviews()
,如果需要由外部事件触发,则事件将在父视图上激发setNeedsLayout()
如果必须在代码中完成,则需要进行大量的握手和配置。我看您希望在
CenterX
和页边距前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])
希望这有帮助 将contentMode
设置为ScaleAspectFit//contents scaled以适应固定方面。其余部分是透明的
I确实设置了myImage.contentMode=UIViewContentMode.ScaleAspectFit/外观保持不变,但它超出了框架的定义宽度和高度……您应该为此图像视图
设置约束宽度
和高度
。