简体   繁体   English

如何使大图像适合小图像视图

[英]How to make fit a larger image into the small image view

I have the image view which has fixed size. 我有固定大小的图像视图。 But I want to fit every size of image into this without stretching. 但是我想在不拉伸的情况下将各种尺寸的图像放入其中。

I tried this 我试过了

In method resizeImage, I passed my selected image and size of UIImageView. 在方法resizeImage中,我传递了我选择的图像和UIImageView的大小。

 func resizeImage(image: UIImage, size: CGSize) -> UIImage {

        UIGraphicsBeginImageContext(size)
        image.drawInRect(CGRectMake(0, 0, size.width, size.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }

But this is not working, It is still returning the stretched image. 但这不起作用,它仍在返回拉伸的图像。

Please let me know what could be the proper solution. 请让我知道什么是正确的解决方案。

Thanks 谢谢

I think what you are looking for is your UIImageView 's contentMode property. 我认为您正在寻找的是UIImageViewcontentMode属性。 Like so: 像这样:

myImageView.contentMode = .ScaleAspectFit

This value will make sure that when you set the view's image, the image will fill the view as much as possible without stretching the image. 此值将确保在设置视图的图像时,图像将尽可能多地填充视图而不会拉伸图像。 You could also use .ScaleAspectFill to completely fill the view, but then your image will be cropped. 您也可以使用.ScaleAspectFill完全填充视图,但是图像将被裁剪。

Just do this: 只要这样做:

imageView.contentMode = .ScaleAspectFill

When you do this, two things happen: 当您这样做时,会发生两件事:

  1. the image in the image view keeps the correct aspect ratio (ie it's not stretched), 图像视图中的图像保持正确的宽高比(即未拉伸),
  2. The image fills the image view completely. 图像完全充满了图像视图。 If needed, the center part of the image is cropped. 如果需要,将裁切图像的中心部分。 Eg if your image view is square, and the image is a rectangle, then the image will be cropped to a square. 例如,如果您的图像视图是正方形,并且图像是矩形,则图像将被裁剪为正方形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM