簡體   English   中英

有沒有辦法根據 SWIFT 中的屏幕尺寸自動調整圖像或任何內容的大小?

[英]is there a way to automatically resize an image or any content based on the screen size in SWIFT?

我一直在嘗試找到一種方法來以編程方式根據屏幕尺寸調整圖像大小而不使用情節提要?

Go 到谷歌(或您最喜歡的搜索引擎)並搜索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 上,橫向:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM