iPhone : Getting the size of an image after AspectFt

前端 未结 4 1592
天涯浪人
天涯浪人 2020-12-28 15:04

Real odd one to get stuck on but weirdly I am.

You you have a imageView containing a image. You size that imageView down and then tell it

4条回答
  •  时光取名叫无心
    2020-12-28 15:26

    I have written a quick category on UIImageView to achieve that:

    (.h)

    @interface UIImageView (additions)
    - (CGSize)imageScale;
    @end
    

    (.m)

    @implementation UIImageView (additions)
    - (CGSize)imageScale {
        CGFloat sx = self.frame.size.width / self.image.size.width;
        CGFloat sy = self.frame.size.height / self.image.size.height;
        CGFloat s = 1.0;
        switch (self.contentMode) {
            case UIViewContentModeScaleAspectFit:
                s = fminf(sx, sy);
                return CGSizeMake(s, s);
                break;
    
            case UIViewContentModeScaleAspectFill:
                s = fmaxf(sx, sy);
                return CGSizeMake(s, s);
                break;
    
            case UIViewContentModeScaleToFill:
                return CGSizeMake(sx, sy);
    
            default:
                return CGSizeMake(s, s);
        }
    }
    @end
    

    Multiply the original image size by the given scale, and you'll get your actual displayed image size.

提交回复
热议问题