How to stop an image from stretching within a UIImageView?

佐手、 提交于 2019-11-29 22:01:56
jtbandes

You can use

self.imageView.contentMode = UIViewContentModeScaleAspectFit;

Swift 3:

imageView.contentMode = .scaleAspectFit

Or UIViewContentModeCenter / .center, or any of the other modes described in the UIView documentation.

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

imageView.clipsToBounds = YES;
imageView.contentMode = UIViewContentModeScaleAspectFit;
Anomie

Use the contentMode property. You probably want either UIViewContentModeScaleAspectFit or UIViewContentModeCenter.

Change the UIImage's Mode from 'scale to fill' to 'Center' within the interface builder. Make sure your image is the exact size you need.

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

Update for Swift 3:

imageView.contentMode = .scaleAspectFit

Change the contentMode, e.g.:

imageView.contentMode = UIViewContentModeScaleAspectFit;

How to use original size of image - without any stretching

  • Just change the UIImage's Mode from scale to fill to Aspect Fit within the interface builder.

Baraiya Bhadresh

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.

Daniel Long

still stretch when image is bigger than imageivew

swift

    let qCodeImage = UIImage(named: "qcode-placeholder.png")!      
    let qCodeImageView = UIImageView(frame: CGRectMake(0, 0, CGRectGetWidth(cardView.frame)-30, CGRectGetWidth(cardView.frame)-30))
    qCodeImageView.image = qCodeImage
    qCodeImageView.clipsToBounds = true
    qCodeImageView.contentMode = UIViewContentMode.ScaleToFill
    qCodeImageView.center = cardView.center
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!