daisy
daisy

Reputation: 23581

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.

Upvotes: 0

Views: 99

Answers (2)

Zigii Wong
Zigii Wong

Reputation: 7826

UIImageView inherits from UIView.

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

Upvotes: 2

ravron
ravron

Reputation: 11221

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.

Upvotes: 2

Related Questions