gpt4 book ai didi

ios - 以小于其固有尺寸的尺寸显示 UIImageView

转载 作者:可可西里 更新时间:2023-10-31 23:44:41 26 4
gpt4 key购买 nike

采用自动布局和 Storyboard后,我不再按精确尺寸设计屏幕,所以当我使用图像时,我倾向于使用相当大尺寸的图像,这样它在 iPad 上看起来会很清晰,但可以按比例缩小以适应更小的 iPhone。我将这张图片拖到 Assets 目录中。

当我将图像放入 Storyboard 中的 View Controller 时,图像想要保持其固有大小。我只能通过设置特定宽度、与另一个对象成比例的宽度,或者将它限制在其他两个项目之间来让它显示得更小。

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

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

关于我遗漏的任何想法?谢谢!

最佳答案

我看你想在 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])

希望这对您有所帮助!

关于ios - 以小于其固有尺寸的尺寸显示 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31736678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com