简体   繁体   中英

Resize and center and image with only UIImageView

I'm trying to put a 400x400 image in a UIView .

So I created a UIImageView and limited the image size to 40x40 , then I placed the UIImageView in the centre of the UIView .

Now the question is, can I do that with only a UIImageView ? The only purpose of this extra UIView is to set a background color and centre the image.

A UIImageView alone cannot arbitrarily resize its image. It will respect its contentMode setting , however. I see no particular problem doing what you've described with a UIImageView inside of a UIView . If you're set on using just a UIImageView , though, it could be done in at least two ways:

Option 1: In an external editor, change your 400 x 400 image into a 40 x 40 image.

Option 2: Using UIImage , create a smaller copy of the original 400 x 400 image in your code, so that it's 40 x 40.

After either option 1 or 2, you'll have a 40 x 40 image. Then, set your image view's contentMode to UIViewContentModeCenter , and change the image view's backgroundColor to whatever you want. This will put the image in the view's center, and you can make the view itself whatever size you desire.

UIImageView inherits from UIView .

You can set the background with UIImageView 's property backgroundColor or it's frame as well.

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