简体   繁体   English

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

[英]how to set image in top avoiding space in UIimageView

I've an UIImageView with content mode Aspect Fit of size 220x155. 我有一个UIImageView,其内容模式Aspect Fit的大小为220x155。 I'm dynamically inserting different images in different resolutions, but all larger than the size of the UIImageView. 我正在以不同的分辨率动态插入不同的图像,但都大于UIImageView的大小。 As the content mode is set to Aspect Fit, the image is scaled with respect to the ratio to fit the UIImageView. 当内容模式设置为Aspect Fit时,图像将根据比例进行缩放以适合UIImageView。

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. 我的问题是,如果例如UIImageView中的图像缩放到220x100,我希望UIImageView也从155到100的高度缩小,以避免我的元素之间的空间。

How can I do this? 我怎样才能做到这一点?

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) image view with aspect fit content mode 2) get the exact frame of the image ( this way you can re-position the image view ) 1)具有宽高比适合内容模式的图像视图2)获取图像的精确帧(这样您可以重新定位图像视图)

Hope this helps: 希望这可以帮助:

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

I am using here AsyncImageView but it will work just as good with UIImageView . 我在这里使用AsyncImageView但它与UIImageView一样好用。 The important thing to remember is to call this method AFTER the image was loaded. 要记住的重要一点是在加载图像后调用此方法。

Cheers! 干杯!

Its very simple, you just need to get image actual size, which can be done by 它非常简单,你只需要获得图像的实际尺寸,这可以通过以下方式完成

UIImage *image = [UIImage imageName:@""];

then you just need to set frame Like :- 那么你只需要设置框架像: -

imageView.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);

Hope this helps you. 希望这对你有所帮助。

将imageview的图像设置为新图像(并因此缩放)后,您可以在imageview(imageview.image.size.height)内获取图像的高度,并相应地设置imageview的高度(帧)。

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

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