简体   繁体   中英

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.

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];

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?

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.

Use the contentMode property of UIImageView.


Edit: and set the image size to 300x300 .

 [image setContentMode:UIViewContentModeScaleToFill];

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