繁体   English   中英

如何在 AspectFit 比率后调整 UIImageView 的大小

[英]How to resize the UIImageView after AspectFit ratio

如何在将其 contentmode 设置为UIViewContentModeScaleAspectFit后调整 UIImageView 的大小,以便我可以从顶部和底部删除空格。 请看附件图片
图片

提前致谢:)

希望这也能帮助其他人,如果它在某些情况下会中断,请发表评论:)

- (CGRect)frameForImageattribute:(CGSize)image inImageViewAspectFit:(UIImageView *)imageView {
        float imageRatio = image.width / image.height;
        float viewRatio = imageView.frame.size.width / imageView.frame.size.height;
        if (imageRatio < viewRatio) {
            float scale = imageView.frame.size.height / image.height;
            float width = scale * image.width;
            return CGRectMake(kLeftPading, kTopPading, width, imageView.frame.size.height);
        }
        else {
            float scale = imageView.frame.size.width / image.width;
            float height = scale * image.height;  
            return CGRectMake(kLeftPading, kTopPading, imageView.frame.size.width, height);
        }
}

您需要获取图像视图的比例因子。 它可以通过

float scaleFactor = MAX(image.size.width/imageView.bounds.size.width, image.size.height/imageView.bounds.size.height);

然后做

CGRect ivFrame = imageView.frame;
ivframe.size.height = image.size.height/scalefactor;
ivFrame.size.width = image.size.width/scalefactor;
imageView.frame = ivFrame;

可能有一个类别可以自动执行此操作。

编辑:这是缩放因子计算的一个,它甚至尊重 mageView 的内容模式:

如何获得模式为 AspectFit 的 UIImageView 的比例因子?

如果您只知道 imageview 的宽度并且图像的高度是动态的,那么您需要根据给定的宽度缩放图像的高度,以在 UIViewContentModeScaleAspectFit 模式下删除图像上方和下方的空白区域。 从使用下面的方法在这里根据你的屏幕的标准宽度图像缩放到的高度。

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

暂无
暂无

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

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