how to set image in top avoiding space in UIimageView

青春壹個敷衍的年華 提交于 2019-12-01 04:32:39

问题


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.

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.

How can I do this?


回答1:


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 )

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. The important thing to remember is to call this method AFTER the image was loaded.

Cheers!




回答2:


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.




回答3:


Once the imageview's image is set to the new image (and thus scaled) you can get the height of the image inside the imageview (imageview.image.size.height) and set the imageview's height (frame) accordingly.



来源:https://stackoverflow.com/questions/12711133/how-to-set-image-in-top-avoiding-space-in-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!