How to use xcassets/universal background images fo

2020-07-27 06:09发布

问题:

I would like to display a different background for each different device (i.e. iPhone 4S, iPhone 5, iPhone6, iPhone 6Plus etc.). I am not talking about launch images but app's backgrounds that will be displayed while using the app.

I have added the following code in my ViewController:

var bgImage     = UIImage(named: "main_bg");
var imageView   = UIImageView(frame: self.view.bounds);
imageView.image = bgImage
self.view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)

And I am ready to add the assets into the Images.xcassets catalog.

This is what I see when I create a new "Image set"

Therefore, I am trying to match the assets with each different device.

Thanks to this question: universal image support I now know that these devices will access the following images:

iPhone 3 -> 1x (image size: 320x480px)

iPhone 4/4S/6 -> 2x (image size: 640x960px)

iPhone 5/5c/5s/iPod Touch -> Retina 4 2x (image size: 640x1336)

iPhone 6 Plus -> 3x (image size: 1242 x 2208)

My question is, how can iPhones 4/4s and 6 access the same image if, clearly, it's not in the right size for both devices?

Thank you

回答1:

Try to check this answer: How to handle image scale on all the available iPhone resolutions?

You can use this code to configure a different image as well:

NSNumber *screenWidth = @([UIScreen mainScreen].bounds.size.width);
NSString *imageName = [NSString stringWithFormat:@"name-%@w", screenWidth];
UIImage *image = [UIImage imageNamed:imageName];


标签: ios xcode