RockBaby
RockBaby

Reputation: 381

UIImageView fill in UIView

I have a UIImageView as a subview of UIView (frame size 300 x 300). My UIImage would be either portrait, landscape or some odd sizes. How do I fill in the UIImage within the UIView frame size without stretching the image to 300 x 300?

The purpose of this, I will be adding another UIImageView as the image border. Please help.

Thanks.

Upvotes: 5

Views: 22623

Answers (5)

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73608

Try

[img setContentMode:UIViewContentModeScaleAspectFit];

UIViewContentModeScaleAspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.

or [img setContentMode:UIViewContentModeScaleAspectFill];

UIViewContentModeScaleAspectFill: Scales the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.

if you are clipping subviews, then you need to do

[imgView clipToBounds:YES];

Upvotes: 15

Fang Chen
Fang Chen

Reputation: 236

Ah I just reread what you were asking, I know what your question is now.

Your UIImageView's frame changes, and when it does so does your image. You don't want your image to change, but you do want your ImageView to adjust to fill the view it is contained in.

UPDATE

I figured it out.

[self.imageView setContentMode:UIViewContentModeCenter];

No matter what orientation, the size stays the same.

You also have the option of setting it to align top, bottom, left, right, top left, top right, bottom left, bottom right, all of which only help to align your image and NOT redraw or re-size the image.

Does that help?

Upvotes: 2

calimarkus
calimarkus

Reputation: 9977

Use the contentMode property of UIImageView.


Edit: and set the image size to 300x300.

Upvotes: 0

Oscar Gomez
Oscar Gomez

Reputation: 18488

Set the contentMode property of UIImageView to either of this values depending on where you want to put it in the superview:

 UIViewContentModeCenter,
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,

As this values:

UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,
    UIViewContentModeScaleAspectFill,

Will indeed cause the image to be 300 x 300, which is what you don't want.

Upvotes: 1

Tomasz Szulc
Tomasz Szulc

Reputation: 4235

 [image setContentMode:UIViewContentModeScaleToFill];

Upvotes: 1

Related Questions