iphoneuiimageviewuiimagecontentmodeaspect-fit

How to make border image to be fitted as per aspectfit uiimageview size?


In my application i have 2 uiimageview.one imageview contains the image that user selects either from photo library or take picture from camera.contentmode of this imageview is aspectfit so that image is not stretched if it is of lesser size.There is other imageview which contains image that is border to that first imageview.when user selects a image that is of similar size of imageview then border is appropriate place.but when image is of lesser size border is not coming properly.there is gap between border image and selected photo image.i dont want that gap.How can i fix this?See the attached image.Here i dont want black gap that is between image and frame


Solution

  • The issue got solved by using following code:

    -(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView
    {
        float imageRatio = image.size.width / image.size.height;
    
        float viewRatio = imageView.frame.size.width / imageView.frame.size.height;
    
        if(imageRatio < viewRatio)
        {
            float scale = imageView.frame.size.height / image.size.height;
    
            float width = scale * image.size.width;
    
            float topLeftX = (imageView.frame.size.width - width) * 0.5;
    
            return CGRectMake(topLeftX, 0, width, imageView.frame.size.height);
        }
        else
        {
            float scale = imageView.frame.size.width / image.size.width;
    
            float height = scale * image.size.height;
    
            float topLeftY = (imageView.frame.size.height - height) * 0.5;
    
            return CGRectMake(0, topLeftY, imageView.frame.size.width, height);
        }
    }