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


Answers:


30

请参阅@ 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 x402。当它缩放到宽度时,它将返回402(高度)的缩放大小。我改变了if ( a - x > b - y ) {if ( a - x > b - y && (y/b * a) < x) {解决它。他们的其他陈述也应检查。
renaun 2014年

先生您好,我发现这个豆有益的,但你可以请帮我在我的问题:stackoverflow.com/questions/22727615/...
Mrug

141

为什么不使用OS函数AVMakeRectWithAspectRatioInsideRect


21
这正是需要的- [imageView setFrame:AVMakeRectWithAspectRatioInsideRect(image.size, imageView.frame)]
greg 2013年


不想包括AVFoundation框架吗?我AVMakeRectWithAspectRatioInsideRect()在单独的答案中发布了两个替代实用程序函数。
Timo

1
这应该是公认的答案。上面接受的答案不正确,在不同情况下不起作用。
jjpp 2015年

1
对于更快的用户:导入AVFoundation let height = AVMakeRectWithAspectRatioInsideRect((image?.size)!, imageView.frame).height
Ben Sullivan

53

我想在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);

请注意,图像如何确定纵横比,而图像视图则确定要填充的尺寸。

反馈非常欢迎。


2
CGFloats如果您喜欢这种东西,可以调整为使用。
Timo 2013年

2
极好的答案。您还可以将其调整为以某个视图为中心,以使用AspectFit在UIImageView中获取图像的实际CGRect。我做了这样的事情:<code> 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; </ code>
LilDwarf 2014年

谢谢,这是一个很棒的实用程序功能。
EralpB 2015年

我提供了一个优化版本,可以删除重复的部分。现在,无分支等效可能是一个有趣的挑战。:)
Timo 2015年

17

这个简单的函数将在调整宽高比之后计算图像的大小:

迅捷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的图像内容中获取它。它也可以与方向更改一起使用。谢谢。
Ayan Sengupta

由于这总是在UIImageView上完成,因此可能值得将其整形为类别方法UIImageView。
Timo 2014年

它没有返回精确的帧
Aiyub Munshi

11

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
    }

}

10

我还想在应用纵横比之后计算高度,以便能够计算表格视图单元格的高度。所以,我通过一点数学就达到了

ratio = width / height

和高度将成为

height = width / ratio

所以代码片段是

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;
oyalhi '16

你太聪明了!这应该是公认的答案!
玛丽安·佩特里瑟

9

对于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)

7

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

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

如果查询后图像视图执行sizeToFit imageView.frame.size你会得到新的图像视适合的尺寸新的图像大小。


5
+(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;
}

4

Swift 4:.aspectFit图像 框架为-

import AVFoundation

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


是的,我做到了,但是我在y上没有任何空格,但是它将返回40
Kishore Kumar,

出乎意料的是,您是否尝试过使用具有不受限制的单个imageView的新鲜视图控制器?
杰克

我在uiview xib上尝试过,在那个图像视图中,原点x值将变为y,原始y值将变为x。我正在使用约束。
Kishore Kumar

就像您说的那样,这是一个问题,因为受到限制@Jack
Kishore Kumar

3

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


2

公认的答案非常复杂,并且在某些情况下失败。我认为此解决方案更加优雅:

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


2

这是我的无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)

另外,这是在另一个rect中安装一个rect的另一个扩展(它利用了上面的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
    }
}

1

我在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)

1

如果仅知道imageview的宽度,并且图像的高度是动态的,则需要根据给定的宽度缩放图像的高度,以删除图像上方和下方的空白。从此处使用以下方法根据屏幕的标准宽度缩放图像的高度。

-(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];

1

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

0

上述方法从不给出所需的值,因为宽高比保持相同的宽高比,我们只需要简单的数学即可计算出值

检测宽高比

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;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.