Endore8
Endore8

Reputation: 55

UIImageView image autoscale

I have custom UITableViewCell with 4 UIImageViews it. I set image in UIImageView.image different size, but i want to scale it proportion (without black lines top/bottom and left/right. How can i do it?

Upvotes: 1

Views: 4289

Answers (2)

kalpesh
kalpesh

Reputation: 1287

func resizeImage(image: UIImage) -> UIImage {

    let UpdateWidth = setBannerHeighWidthDynamically(image: image).width
    let newHeight = setBannerHeighWidthDynamically(image: image).height
    UIGraphicsBeginImageContext(CGSize(width: UpdateWidth, height: newHeight))
    image.draw(in: CGRect(x: 0.0, y: 0.0, width: UpdateWidth, height: newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}
 func setBannerHeighWidthDynamically(image: UIImage)->(width:CGFloat, height:CGFloat)
{
    let img_original_height = image.size.height
    let img_original_width = image.size.width

    if (img_original_height < img_original_width) {

        let width = getScreenMesure(isLandScap: true)
        let height = CGFloat(img_original_height) * width / CGFloat(img_original_width)

        return (width, height)

    }else{
        //best result 4/5
        var height = getScreenMesure(isLandScap: false) * 2 / 3
        if (CGFloat(img_original_height) >= height) {

            var width = CGFloat(img_original_width) * height / CGFloat(img_original_height)
            if (width > getScreenMesure(isLandScap: true)){
                width = getScreenMesure(isLandScap: true)
                height = (width * CGFloat(img_original_height)) / CGFloat(img_original_width);
                return (width, height)

            }else{
                return (width, height)

            }


        }else{
            var width = (CGFloat(img_original_width) * height) / CGFloat(img_original_height);
            if (width > getScreenMesure(isLandScap: true)) {
                width = getScreenMesure(isLandScap: true)
                height = (width * CGFloat(img_original_height)) / CGFloat(img_original_width);
                return (width, height)
            }else{
                return (width, height)
            }
        }
    }
}
func getScreenMesure(isLandScap:Bool)->CGFloat{
    if isLandScap{
        return UIScreen.main.bounds.size.width
    }else{
        return UIScreen.main.bounds.size.height
    }
}

And you can call like this.

let PropotionalImage = self.resizeImage(image: UIImage(named: "YourImageName"))

Upvotes: 0

Sj.
Sj.

Reputation: 1724

You can use the contentMode property to get your image scaled.

If you want to fit your image in the imageview frame wrt to its aspect ratio, set

imageView.contentMode = UIViewContentModeScaleAspectFit. Also try with AspectFill too.

Set the backgroundColor of the imageView to clearColor;

Upvotes: 5

Related Questions