如何在顶部设置图像避免 UIimageView 中的空间

how to set image in top avoiding space in UIimageView(如何在顶部设置图像避免 UIimageView 中的空间)

本文介绍了如何在顶部设置图像避免 UIimageView 中的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容模式 Aspect Fit 大小为 220x155 的 UIImageView.我正在以不同的分辨率动态插入不同的图像,但都大于 UIImageView 的大小.由于内容模式设置为 Aspect Fit,图像会根据比例缩放以适合 UIImageView.

I've an UIImageView with content mode Aspect Fit of size 220x155. I'm dynamically inserting different images in different resolutions, but all larger than the size of the UIImageView. As the content mode is set to Aspect Fit, the image is scaled with respect to the ratio to fit the UIImageView.

我的问题是,例如,如果 UIImageView 内的图像缩放到 220x100,我希望 UIImageView 也从 155 的高度缩小到 100 以避免元素之间的空间.

My problem is, that if for instance the image inside the UIImageView is scaled to 220x100, I would like the UIImageView to shrink from a height of 155 to 100 too to avoid space between my elements.

我该怎么做?

推荐答案

我写这个方法是为了在加载图像后获取图像视图的框架.所以,我的要求和你的一样:

I wrote this method to get me the frame of the image view once it loaded an image. So , the requirements for me were the same as in your case:

1) 具有宽高比内容模式的图像视图2)获取图像的确切帧(这样您可以重新定位图像视图)

1) image view with aspect fit content mode 2) get the exact frame of the image ( this way you can re-position the image view )

希望这会有所帮助:

- (CGRect) getFrameOfImage:(AsyncImageView *) imgView
{
    if(!imgView.loaded)
        return CGRectZero;

    CGSize imgSize      = imgView.image.size;
    CGSize frameSize    = imgView.frame.size;

    CGRect resultFrame;

    if(imgSize.width < frameSize.width && imgSize.height < frameSize.height)
    {
        resultFrame.size    = imgSize;
    }
    else
    {
        float widthRatio  = imgSize.width  / frameSize.width;
        float heightRatio = imgSize.height / frameSize.height;

        float maxRatio = MAX (widthRatio , heightRatio);
        NSLog(@"widthRatio = %.2f , heightRatio = %.2f , maxRatio = %.2f" , widthRatio , heightRatio , maxRatio);

        resultFrame.size = CGSizeMake(imgSize.width / maxRatio, imgSize.height / maxRatio);
    }

    resultFrame.origin  = CGPointMake(imgView.center.x - resultFrame.size.width/2 , imgView.center.y - resultFrame.size.height/2);

    return resultFrame;
}

我在这里使用 AsyncImageView,但它与 UIImageView 一样好用.要记住的重要一点是在加载图像后调用此方法.

I am using here AsyncImageView but it will work just as good with UIImageView. The important thing to remember is to call this method AFTER the image was loaded.

干杯!

这篇关于如何在顶部设置图像避免 UIimageView 中的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在顶部设置图像避免 UIimageView 中的空间

基础教程推荐