简体   繁体   English

根据屏幕尺寸设置UIImageView宽度

[英]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. 我正在尝试将图像的宽度设置为屏幕宽度的75%,并位于中间。

  1. I've tried to get the screen size 我试图获取屏幕尺寸
  2. I've tried to assign the size.width to my image 我尝试将size.width分配给我的图片

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! 由于图像是UIImage而不是CGFloat! (sWidth is CGFloat) (sWidth为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: 在imageView和viewController的视图之间添加以下约束:

  1. equal height 等高
  2. equal width with multiplier of 0.75 宽度等于0.75的倍数

Also -> try using the storyboard more: add the image to the imageView through the storyboard. 另外->尝试更多使用故事板:通过故事板将图像添加到imageView中。

if you don't want to do this, add it in code inside viewDidLoad. 如果您不想这样做,请将其添加到viewDidLoad中的代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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