简体   繁体   中英

Setting UIImageView Width According To Screen Size

I am trying to set an image's width to 75% of the screen width and positioned in the middle.

  1. I've tried to get the screen size
  2. I've tried to assign the size.width to my image

class ViewController: UIViewController {

    @IBOutlet weak var logo: UIImageView!

    var sSize: CGRect = UIScreen.mainScreen().bounds
    let sWidth = sSize.width
    var image = UIImage(named: "logo");
    image = sWidth * 0.75

    @IBAction func btnPlay(sender: AnyObject) {
        logo.hidden = true
    }

}

This following line shouldn't compile:

image = sWidth * 0.75

Since image is a UIImage and not a CGFloat! (sWidth is CGFloat)

Change your code as follow:

class ViewController: UIViewController {
    @IBOutlet weak var logo: UIImageView!
}

And in the storyboard use autolayout:

add a these constraints between the imageView and the viewController's view:

  1. equal height
  2. equal width with multiplier of 0.75

Also -> try using the storyboard more: add the image to the imageView through the storyboard.

if you don't want to do this, add it in code inside viewDidLoad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM