【发布时间】:2021-01-06 17:26:06
【问题描述】:
我一直在尝试找到一种方法来以编程方式根据屏幕尺寸调整图像大小而不使用情节提要?
【问题讨论】:
-
imageView.frame = view.bounds。当您将 imageView 添加到主视图时,您可以添加此代码。
标签: swift autolayout
我一直在尝试找到一种方法来以编程方式根据屏幕尺寸调整图像大小而不使用情节提要?
【问题讨论】:
标签: swift autolayout
转到 google(或您最喜欢的搜索引擎)并搜索 swift add constraints programmatically。这是非常非常基本的。
这是一个简单的例子:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create image view
let imgView = UIImageView()
imgView.backgroundColor = .systemYellow
// create image
let img = UIImage(systemName: "person.fill")
imgView.image = img
// add imageView to view
view.addSubview(imgView)
// use auto-layout
imgView.translatesAutoresizingMaskIntoConstraints = false
// respect safe area
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// constrain imageView width to view safe-area width
imgView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
imgView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
// aquare image view (1:1 ratio)
imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor),
// center vertically
imgView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
])
}
}
结果:
编辑 - 第二个例子...前三分之一,水平居中:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(true, animated: false)
// create image view
let imgView = UIImageView()
imgView.backgroundColor = .systemYellow
// create image
let img = UIImage(systemName: "person.fill")
imgView.image = img
// add imageView to view
view.addSubview(imgView)
// use auto-layout
imgView.translatesAutoresizingMaskIntoConstraints = false
// respect safe area
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// you want the image view at the top?
imgView.topAnchor.constraint(equalTo: g.topAnchor),
// one-third of the height of the view?
imgView.heightAnchor.constraint(equalTo: g.heightAnchor, multiplier: 1.0 / 3.0),
// you want a aquare image view (1:1 ratio)?
imgView.widthAnchor.constraint(equalTo: imgView.heightAnchor),
// you want it centered horizontally?
imgView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
])
}
}
在 iPhone 8 上:
在 iPhone 12 上:
在 9.7 英寸 iPad Pro 上,横向:
【讨论】: