How to stop an image from stretching within a UIIm

2020-02-17 04:30发布

I have a UIImageView where I have set the frame size to x = 0, y = 0, width = 404, height = 712. In my project, I need to change the image in UIImageView dynamically.

I am using this code to change the image:

self.imageView.image = [UIImage imageNamed:@"setting-image.png"];

The problem is, when the *.png image size is smaller than the UIImageView frame size, the image stretches. I don't want it to stretch. Is there any way to do that?

10条回答
混吃等死
2楼-- · 2020-02-17 05:14

Update for Swift 3:

imageView.contentMode = .scaleAspectFit
查看更多
\"骚年 ilove
3楼-- · 2020-02-17 05:16

You have to set CGSize as your image width and hight so image will not stretch and it will arrange at the middle of imageview.

- (UIImage *)imageWithImage:(UIImage *)image scaledToFillSize:(CGSize)size
{
    CGFloat scale = MAX(size.width/image.size.width, size.height/image.size.height);
    CGFloat width = image.size.width * scale;
    CGFloat height = image.size.height * scale;
    CGRect imageRect = CGRectMake((size.width - width)/2.0f,
                                  (size.height - height)/2.0f,
                                  width,
                                  height);

    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    [image drawInRect:imageRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
查看更多
我只想做你的唯一
4楼-- · 2020-02-17 05:21

Setting clipsToBounds in combination with UIViewContentModeScaleAspectFit contentMode was what did the trick for me. Hope that helps someone!

imageView.clipsToBounds = YES;
imageView.contentMode = UIViewContentModeScaleAspectFit;
查看更多
Ridiculous、
5楼-- · 2020-02-17 05:21

Use this for your UIImageView

imageView.contentMode = UIViewContentModeScaleAspectFill;

You won't get any space and with scale preserved. However, some part of the image will be clipped off.

If you use the following:

imageView.contentMode = UIViewContentModeScaleAspectFit;

There will be some empty space, but scale is preserved.

查看更多
登录 后发表回答