how to set image in top avoiding space in UIimageView

前端 未结 3 1918
孤城傲影
孤城傲影 2021-01-13 21:00

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

3条回答
  •  旧巷少年郎
    2021-01-13 21:31

    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!

提交回复
热议问题