How to stop an image from stretching within a UIImageView?

前端 未结 10 2339
北恋
北恋 2020-12-23 19:10

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

相关标签:
10条回答
  • 2020-12-23 19:17

    Update for Swift 3:

    imageView.contentMode = .scaleAspectFit
    
    0 讨论(0)
  • 2020-12-23 19:26

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

    0 讨论(0)
  • 2020-12-23 19:28

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

    imageView.clipsToBounds = YES;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    0 讨论(0)
  • 2020-12-23 19:30

    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.

    0 讨论(0)
  • 2020-12-23 19:31

    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;
    }
    
    0 讨论(0)
  • 2020-12-23 19:31

    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.

    0 讨论(0)
提交回复
热议问题