在 UIImageView 中应用适合图像的宽高比后如何知道图像大小

Posted

技术标签:

【中文标题】在 UIImageView 中应用适合图像的宽高比后如何知道图像大小【英文标题】:How to know the image size after applying aspect fit for the image in an UIImageView 【发布时间】:2011-09-10 20:31:15 【问题描述】:

我正在将图像加载到模式为“Aspect Fit”的图像视图中。我需要知道我的图像被缩放到的大小。请帮忙。

【问题讨论】:

【参考方案1】:

Swift 5 扩展

extension CGSize 
    func aspectFit(to size: CGSize) -> CGSize 
        let mW = size.width / self.width;
        let mH = size.height / self.height;
        
        var result = size
        if( mH < mW ) 
            result.width = size.height / self.height * self.width;
        
        else if( mW < mH ) 
            result.height = size.width / self.width * self.height;
        
        
        return result;
    
    
    func aspectFill(to size: CGSize) -> CGSize 
        let mW = size.width / self.width;
        let mH = size.height / self.height;
        
        var result = size
        if( mH > mW ) 
            result.width = size.height / self.height * self.width;
        
        else if( mW > mH ) 
            result.height = size.width / self.width * self.height;
        
        return result;
    

【讨论】:

【参考方案2】:

这个简单的函数将计算宽高比拟合后的图像大小:

斯威夫特 5.1

extension UIImageView 

    var imageSizeAfterAspectFit: CGSize 
        var newWidth: CGFloat
        var newHeight: CGFloat

        guard let image = image else  return frame.size 

        if image.size.height >= image.size.width 
            newHeight = frame.size.height
            newWidth = ((image.size.width / (image.size.height)) * newHeight)

            if CGFloat(newWidth) > (frame.size.width) 
                let diff = (frame.size.width) - newWidth
                newHeight = newHeight + CGFloat(diff) / newHeight * newHeight
                newWidth = frame.size.width
            
         else 
            newWidth = frame.size.width
            newHeight = (image.size.height / image.size.width) * newWidth

            if newHeight > frame.size.height 
                let diff = Float((frame.size.height) - newHeight)
                newWidth = newWidth + CGFloat(diff) / newWidth * newWidth
                newHeight = frame.size.height
            
        
        return .init(width: newWidth, height: newHeight)
    

目标 C:

 -(CGSize)imageSizeAfterAspectFit:(UIImageView*)imgview


    float newwidth;
    float newheight;

    UIImage *image=imgview.image;

    if (image.size.height>=image.size.width)
        newheight=imgview.frame.size.height;
        newwidth=(image.size.width/image.size.height)*newheight;

        if(newwidth>imgview.frame.size.width)
            float diff=imgview.frame.size.width-newwidth;
            newheight=newheight+diff/newheight*newheight;
            newwidth=imgview.frame.size.width;
        

    
    else
        newwidth=imgview.frame.size.width;
        newheight=(image.size.height/image.size.width)*newwidth;

        if(newheight>imgview.frame.size.height)
            float diff=imgview.frame.size.height-newheight;
            newwidth=newwidth+diff/newwidth*newwidth;
            newheight=imgview.frame.size.height;
        
    

    NSLog(@"image after aspect fit: width=%f height=%f",newwidth,newheight);


    //adapt UIImageView size to image size
    //imgview.frame=CGRectMake(imgview.frame.origin.x+(imgview.frame.size.width-newwidth)/2,imgview.frame.origin.y+(imgview.frame.size.height-newheight)/2,newwidth,newheight);

    return CGSizeMake(newwidth, newheight);


【讨论】:

接受的答案对我不起作用。但是这个答案做到了。而这个答案的真正美妙之处在于它不需要传递 UIImage 的任何显式引用,而是从 UIImageView 的图像内容中获取它。它也适用于方向变化。谢谢。 由于这总是在 UIImageView 上完成,因此可能值得将其塑造成一个类别方法 UIImageView。 它没有返回精确的帧【参考方案3】:

这一行就可以完成这项工作

CGSize sizeInView = AVMakeRectWithAspectRatioInsideRect(imgViewFake.image.size, imgViewFake.bounds).size;

【讨论】:

【参考方案4】:

Swift 4 版本

extension CGSize 
   enum AspectMode 
       case fit
       case fill
   

   enum Orientation 
       case portrait
       case landscape
   

   func aspectCorrectSizeToFit(targetSize: CGSize, aspectMode: AspectMode = .fill) -> CGSize 
        switch aspectMode 
        case .fill: return aspectFill(targetSize: targetSize)
        case .fit: return aspectFit(targetSize: targetSize)
        
    

    var orientation: Orientation 
        if height >= width  return .portrait 
        else  return .landscape 
    

    func aspectFit(targetSize: CGSize) -> CGSize 
        let wRatio = targetSize.width / width
        let hRatio = targetSize.height / height
        let scale = min(wRatio, hRatio)
        return applying(CGAffineTransform(scaleX: scale, y: scale))
    

    func aspectFill(targetSize: CGSize) -> CGSize 
        let wRatio = targetSize.width / width
        let hRatio = targetSize.height / height
        let scale = max(wRatio, hRatio)
        return applying(CGAffineTransform(scaleX: scale, y: scale))
    

【讨论】:

【参考方案5】:

为什么不使用操作系统功能AVMakeRectWithAspectRatioInsideRect?

【讨论】:

这正是我们所需要的——[imageView setFrame:AVMakeRectWithAspectRatioInsideRect(image.size, imageView.frame)]) 好和干净的选择。这是文档链接developer.apple.com/library/ios/#documentation/AVFoundation/… 不想包含 AVFoundation 框架?我在单独的答案中向AVMakeRectWithAspectRatioInsideRect() 发布了两个替代实用程序函数。 这应该是公认的答案。上面接受的答案不正确,在不同情况下都不起作用。 对于 swifters:import AVFoundation let height = AVMakeRectWithAspectRatioInsideRect((image?.size)!, imageView.frame).height【参考方案6】:

斯威夫特 4: .aspectFit 图像的框架是 -

import AVFoundation

let x: CGRect = AVMakeRect(aspectRatio: myImage.size, insideRect: sampleImageView.frame)

【讨论】:

是的,我完成了,但我在 y 上没有任何空间,但它返回为 40 这出乎意料,您是否尝试过使用没有约束的单个 imageView 的新视图控制器? 我在 uiview xib 上试过,在那个图像视图中,原点 x 值将变为 y,而原点 y 值将变为 x。我正在使用约束。 就像你说的那样,由于@Jack 的限制,这是一个问题【参考方案7】:

这是我的无 AVFoundation 解决方案。

首先这里是一个 CGSize 扩展,用于计算适合其他尺寸的尺寸:

extension CGSize

    func sizeThatFitsSize(_ aSize: CGSize) -> CGSize
    
        let width = min(self.width * aSize.height / self.height, aSize.width)
        return CGSize(width: width, height: self.height * width / self.width)
    

所以 OP 问题的解决方案归结为:

let resultSize = image.size.sizeThatFitsSize(imageView.bounds.size)

还有另一个扩展,用于在另一个矩形中拟合矩形(它利用上述 CGSize 扩展):

extension CGRect

    func rectThatFitsRect(_ aRect:CGRect) -> CGRect
    
        let sizeThatFits = self.size.sizeThatFitsSize(aRect.size)

        let xPos = (aRect.size.width - sizeThatFits.width) / 2
        let yPos = (aRect.size.height - sizeThatFits.height) / 2

        let ret = CGRect(x: xPos, y: yPos, width: sizeThatFits.width, height: sizeThatFits.height)
        return ret
    

【讨论】:

【参考方案8】:

如果您只知道图像视图的宽度并且图像的高度是动态的,那么您需要根据给定的宽度缩放图像的高度,以删除图像上方和下方的空白。使用here中的以下方法,根据屏幕的标准宽度缩放图像的高度。

-(UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth: (float) i_width

    float oldWidth = sourceImage.size.width;
    float scaleFactor = i_width / oldWidth;

    float newHeight = sourceImage.size.height * scaleFactor;
    float newWidth = oldWidth * scaleFactor;

    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;

然后从你的 cellForRowAtIndexPath: 方法中调用它,如下所示:

UIImage *img = [dictImages objectForKey:yourImageKey]; // loaded the image
cell.imgView.image = [self imageWithImage:img scaledToWidth:self.view.frame.size.width];

【讨论】:

【参考方案9】:

Swift 3 UIImageView 扩展:

import AVFoundation

extension UIImageView 
  var imageSize: CGSize 
    if let image = image 
      return AVMakeRect(aspectRatio: image.size, insideRect: bounds).size
    
    return CGSize.zero
    

【讨论】:

【参考方案10】:

Swift 3人类可读版本

extension UIImageView 

    /// Find the size of the image, once the parent imageView has been given a contentMode of .scaleAspectFit
    /// Querying the image.size returns the non-scaled size. This helper property is needed for accurate results.
    var aspectFitSize: CGSize 
        guard let image = image else  return CGSize.zero 

        var aspectFitSize = CGSize(width: frame.size.width, height: frame.size.height)
        let newWidth: CGFloat = frame.size.width / image.size.width
        let newHeight: CGFloat = frame.size.height / image.size.height

        if newHeight < newWidth 
            aspectFitSize.width = newHeight * image.size.width
         else if newWidth < newHeight 
            aspectFitSize.height = newWidth * image.size.height
        

        return aspectFitSize
    

    /// Find the size of the image, once the parent imageView has been given a contentMode of .scaleAspectFill
    /// Querying the image.size returns the non-scaled, vastly too large size. This helper property is needed for accurate results.
    var aspectFillSize: CGSize 
        guard let image = image else  return CGSize.zero 

        var aspectFillSize = CGSize(width: frame.size.width, height: frame.size.height)
        let newWidth: CGFloat = frame.size.width / image.size.width
        let newHeight: CGFloat = frame.size.height / image.size.height

        if newHeight > newWidth 
            aspectFillSize.width = newHeight * image.size.width
         else if newWidth > newHeight 
            aspectFillSize.height = newWidth * image.size.height
        

        return aspectFillSize
    


【讨论】:

图片原点位置而不是Size怎么样?【参考方案11】:

请看@Paul-de-Lange 的回答,而不是这个


我在一个易于访问的变量中找不到任何东西,所以这是蛮力方法:

- (CGSize) aspectScaledImageSizeForImageView:(UIImageView *)iv image:(UIImage *)im 

float x,y;
float a,b;
x = iv.frame.size.width;
y = iv.frame.size.height;
a = im.size.width;
b = im.size.height;

if ( x == a && y == b )            // image fits exactly, no scaling required
    // return iv.frame.size;

else if ( x > a && y > b )          // image fits completely within the imageview frame
    if ( x-a > y-b )               // image height is limiting factor, scale by height
        a = y/b * a;
        b = y;
     else 
        b = x/a * b;                // image width is limiting factor, scale by width
        a = x;
    
 
else if ( x < a && y < b )         // image is wider and taller than image view
    if ( a - x > b - y )           // height is limiting factor, scale by height
        a = y/b * a;
        b = y;
     else                         // width is limiting factor, scale by width
        b = x/a * b;
        a = x;
    

else if ( x < a && y > b )         // image is wider than view, scale by width
    b = x/a * b;
    a = x;

else if ( x > a && y < b )         // image is taller than view, scale by height
    a = y/b * a;
    b = y;

else if ( x == a ) 
    a = y/b * a;
    b = y;
 else if ( y == b ) 
    b = x/a * b;
    a = x;

return CGSizeMake(a,b);


【讨论】:

此代码不准确。它不能处理所有情况。例如,如果您有一个 2048 x 1536 的图像并尝试适应 514 x 402。当它应该将其缩放到宽度时,它将返回 402(高度)的缩放大小。我将if ( a - x &gt; b - y ) 更改为if ( a - x &gt; b - y &amp;&amp; (y/b * a) &lt; x) 来修复它。他们的其他陈述也应该检查。 您好,先生,我发现这个 Anser 很有帮助,但您能帮我解决我的问题吗:***.com/questions/22727615/…【参考方案12】:

对于 Swift 使用下面的代码

func imageSizeAspectFit(imgview: UIImageView) -> CGSize 
        var newwidth: CGFloat
        var newheight: CGFloat
        let image: UIImage = imgFeed.image!

        if image.size.height >= image.size.width 
            newheight = imgview.frame.size.height;
            newwidth = (image.size.width / image.size.height) * newheight
            if newwidth > imgview.frame.size.width 
                let diff: CGFloat = imgview.frame.size.width - newwidth
                newheight = newheight + diff / newheight * newheight
                newwidth = imgview.frame.size.width
            
        
        else 
            newwidth = imgview.frame.size.width
            newheight = (image.size.height / image.size.width) * newwidth
            if newheight > imgview.frame.size.height 
                let diff: CGFloat = imgview.frame.size.height - newheight
                newwidth = newwidth + diff / newwidth * newwidth
                newheight = imgview.frame.size.height
            
        

       print(newwidth, newheight)
        //adapt UIImageView size to image size
        return CGSizeMake(newwidth, newheight)
    

并调用函数

imgFeed.sd_setImageWithURL(NSURL(string:"Your image URL")))
self.imageSizeAfterAspectFit(imgFeed)

【讨论】:

【参考方案13】:

上述方法从未给出所需的值。由于纵横比保持相同的纵横比,我们只需要简单的数学来计算值

检测纵横比

CGFloat imageViewAspectRatio = backgroundImageView.bounds.size.width / backgroundImageView.bounds.size.height;
CGFloat imageAspectRatio =  backgroundImageView.image.size.width / backgroundImageView.image.size.height;
CGFloat mulFactor = imageViewAspectRatio/imageAspectRatio;

获取新值

CGFloat newImageWidth = mulFactor * backgroundImageView.bounds.size.width;
CGFloat newImageHeight = mulFactor * backgroundImageView.bounds.size.height;

【讨论】:

【参考方案14】:

我在 Swift 中使用以下内容:

private func CGSizeAspectFit(aspectRatio:CGSize,boundingSize:CGSize) -> CGSize

    var aspectFitSize = boundingSize
    let mW = boundingSize.width / aspectRatio.width
    let mH = boundingSize.height / aspectRatio.height
    if( mH < mW )
    
        aspectFitSize.width = mH * aspectRatio.width
    
    else if( mW < mH )
    
        aspectFitSize.height = mW * aspectRatio.height
    
    return aspectFitSize


private func CGSizeAspectFill(aspectRatio:CGSize,minimumSize:CGSize) -> CGSize

    var aspectFillSize = minimumSize
    let mW = minimumSize.width / aspectRatio.width
    let mH = minimumSize.height / aspectRatio.height
    if( mH > mW )
    
        aspectFillSize.width = mH * aspectRatio.width
    
    else if( mW > mH )
    
        aspectFillSize.height = mW * aspectRatio.height
    
    return aspectFillSize

我是这样使用的:

let aspectSize  = contentMode == .ScaleAspectFill ? CGSizeAspectFill(oldSize,minimumSize: newSize) : CGSizeAspectFit(oldSize, boundingSize: newSize)

let newRect = CGRect( x: (newSize.width - aspectSize.width)/2, y: (newSize.height - aspectSize.height)/2, width: aspectSize.width, height: aspectSize.height)

CGContextSetFillColorWithColor(context,IOSXColor.whiteColor().CGColor)
CGContextFillRect(context, CGRect(origin: CGPointZero,size: newSize))
CGContextDrawImage(context, newRect, cgImage)

【讨论】:

【参考方案15】:

我想使用AVMakeRectWithAspectRatioInsideRect() 不包括 AVFoundation 框架

所以我实现了以下两个实用功能:

CGSize CGSizeAspectFit(CGSize aspectRatio, CGSize boundingSize)

    float mW = boundingSize.width / aspectRatio.width;
    float mH = boundingSize.height / aspectRatio.height;
    if( mH < mW )
        boundingSize.width = boundingSize.height / aspectRatio.height * aspectRatio.width;
    else if( mW < mH )
        boundingSize.height = boundingSize.width / aspectRatio.width * aspectRatio.height;
    return boundingSize;


CGSize CGSizeAspectFill(CGSize aspectRatio, CGSize minimumSize)

    float mW = minimumSize.width / aspectRatio.width;
    float mH = minimumSize.height / aspectRatio.height;
    if( mH > mW )
        minimumSize.width = minimumSize.height / aspectRatio.height * aspectRatio.width;
    else if( mW > mH )
        minimumSize.height = minimumSize.width / aspectRatio.width * aspectRatio.height;
    return minimumSize;

编辑:通过删除重复的分区在下方进行了优化。

CGSize CGSizeAspectFit(const CGSize aspectRatio, const CGSize boundingSize)

    CGSize aspectFitSize = CGSizeMake(boundingSize.width, boundingSize.height);
    float mW = boundingSize.width / aspectRatio.width;
    float mH = boundingSize.height / aspectRatio.height;
    if( mH < mW )
        aspectFitSize.width = mH * aspectRatio.width;
    else if( mW < mH )
        aspectFitSize.height = mW * aspectRatio.height;
    return aspectFitSize;


CGSize CGSizeAspectFill(const CGSize aspectRatio, const CGSize minimumSize)

    CGSize aspectFillSize = CGSizeMake(minimumSize.width, minimumSize.height);
    float mW = minimumSize.width / aspectRatio.width;
    float mH = minimumSize.height / aspectRatio.height;
    if( mH > mW )
        aspectFillSize.width = mH * aspectRatio.width;
    else if( mW > mH )
        aspectFillSize.height = mW * aspectRatio.height;
    return aspectFillSize;

编辑结束

这采用给定的大小(第一个参数)并保持其纵横比。然后它在不违反纵横比的情况下尽可能地填充给定的边界(第二个参数)。

用这个来回答原来的问题:

// Using aspect fit, scale the image (size) to the image view's size.
CGSize sizeBeingScaledTo = CGSizeAspectFit(theImage.size, theImageView.frame.size);

注意图像如何决定纵横比,而图像视图决定要填充的大小。

非常欢迎反馈。

【讨论】:

如果你喜欢这样的事情,可以调整为使用CGFloats 优秀的答案。您还可以将其调整为以某个视图为中心,以使用 AspectFit 获取 UIImageView 内图像的实际 CGRect。我做了这样的事情: CGSize imageSize = CGSizeAspectFit(imageView.image.size, imageView.frame.size); CGRect actualImageRect = CGRectMake(0, 0, imageSize.width, imageSize.height); actualImageRect.origin.x = imageView.center.x - imageSize.width / 2; actualImageRect.origin.y = imageView.center.y - imageSize.height / 2; 谢谢,这是一个很棒的实用功能。 我已经包含了一个优化版本,可以删除重复的部门。现在想出一个无分支的等价物可能是一个有趣的挑战。 :)【参考方案16】:

我还想在应用纵横比后计算高度,以便能够计算表格视图单元格的高度。所以,我通过小数学实现了

ratio = width / height

高度会变成

height = width / ratio

所以代码 sn-p 将是

UIImage *img = [UIImage imageNamed:@"anImage"];
float aspectRatio = img.size.width/img.size.height;
float requiredHeight = self.view.bounds.size.width / aspectRatio;

【讨论】:

优雅。我在UITableViewCell 类中使用它,所以requiredHeight 变为float requiredHeight = self.bounds.size.width / aspectRatio; 你太棒了!这应该是公认的答案!【参考方案17】:

这是我针对相同问题的解决方案: https://github.com/alexgarbarev/UIImageView-ImageFrame

优点:

支持 UIViewContentMode 模式 可以分别查询比例和矩形 可以直接从 UIImageView 询问图像框架

【讨论】:

【参考方案18】:

接受的答案非常复杂,并且在某些极端情况下会失败。我认为这个解决方案更加优雅:

- (CGSize) sizeOfImage:(UIImage*)image inAspectFitImageView:(UIImageView*)imageView

    UKAssert(imageView.contentMode == UIViewContentModeScaleAspectFit, @"Image View must use contentMode = UIViewContentModeScaleAspectFit");

    CGFloat imageViewWidth = imageView.bounds.size.width;
    CGFloat imageViewHeight = imageView.bounds.size.height;

    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;

    CGFloat scaleFactor = MIN(imageViewWidth / imageWidth, imageViewHeight / imageHeight);

    return CGSizeMake(image.size.width*scaleFactor, image.size.height*scaleFactor);

【讨论】:

【参考方案19】:

也许不适合您的情况,但这种简单的方法在类似情况下解决了我的问题:

    UIImageView *imageView = [[UIImageView alloc] initWithImage:bigSizeImage];
    [imageView sizeToFit];

image view 执行 sizeToFit 后,如果您查询 imageView.frame.size,您将获得适合新图像尺寸的新 image view 尺寸。

【讨论】:

【参考方案20】:
+(UIImage *)CreateAResizeImage:(UIImage *)Img ThumbSize:(CGSize)ThumbSize 

    float actualHeight = Img.size.height;
    float actualWidth = Img.size.width;

    if(actualWidth==actualHeight) 
    
        actualWidth = ThumbSize.width; 
        actualHeight = ThumbSize.height;
    

    float imgRatio = actualWidth/actualHeight;
    float maxRatio = ThumbSize.width/ThumbSize.height; //320.0/480.0;


    if(imgRatio!=maxRatio)
    
        if(imgRatio < maxRatio)
        
            imgRatio = ThumbSize.height / actualHeight; //480.0 / actualHeight;
            actualWidth = imgRatio * actualWidth;
            actualHeight = ThumbSize.height; //480.0;
        
        else
        
            imgRatio = ThumbSize.width / actualWidth; //320.0 / actualWidth;
            actualHeight = imgRatio * actualHeight;
            actualWidth = ThumbSize.width; //320.0;
        
     
    else 
    
        actualWidth = ThumbSize.width;
        actualHeight = ThumbSize.height; 
    


    CGRect rect = CGRectMake(0, 0, (int)actualWidth, (int)actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [Img drawInRect:rect];
    UIImage *NewImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return NewImg;

【讨论】:

以上是关于在 UIImageView 中应用适合图像的宽高比后如何知道图像大小的主要内容,如果未能解决你的问题,请参考以下文章

使UIImageView适合屏幕宽度但保持纵横比[swift]

如何找到适合预定尺寸的宽高比 4:3 的尺寸?

在方面适合后从 UIImageView 获取图像的宽度和高度

ImageMagick:如何将图像最小化为特定宽高比?

使用Xcode 6中的AutoLayout约束模拟方面适合行为

即使海报图像的宽高比与其视频元素不同,如何用海报图像填充视频元素? [复制]