UIImage size in UIImageView

前端 未结 4 490
天涯浪人
天涯浪人 2021-01-06 18:40

I have some UIImage and display it in UIImageView.

I need to use UIViewContentModeScaleAspectFit content mode.

Here i

4条回答
  •  臣服心动
    2021-01-06 19:06

    Here's a category on UIImageView that you can use to introspect the bounds of the displayed image based on the UIViewContentMode set on the image view:

    @implementation UIImageView (JRAdditions)
    
    - (CGRect)displayedImageBounds {
        UIImage *image = [self image];
        if(self.contentMode != UIViewContentModeScaleAspectFit || !image)
            return CGRectInfinite;
    
        CGFloat boundsWidth  = [self bounds].size.width,
                boundsHeight = [self bounds].size.height;
    
        CGSize  imageSize  = [image size];
        CGFloat imageRatio = imageSize.width / imageSize.height;
        CGFloat viewRatio  = boundsWidth / boundsHeight;
    
        if(imageRatio < viewRatio) {
            CGFloat scale = boundsHeight / imageSize.height;
            CGFloat width = scale * imageSize.width;
            CGFloat topLeftX = (boundsWidth - width) * 0.5;
            return CGRectMake(topLeftX, 0, width, boundsHeight);
        }
    
        CGFloat scale = boundsWidth / imageSize.width;
        CGFloat height = scale * imageSize.height;
        CGFloat topLeftY = (boundsHeight - height) * 0.5;
    
        return CGRectMake(0, topLeftY, boundsWidth, height);
    }
    
    @end
    

提交回复
热议问题