1

我有自定义 UITableViewCell 和 4 UIImageViews 它。我在 UIImageView.image 中设置了不同大小的图像,但我想按比例缩放它(没有黑线顶部/底部和左/右。我该怎么做?

4

2 回答 2

5

您可以使用 contentMode 属性来缩放图像。

如果您想将图像放入 imageview 框架中以适应其纵横比,请设置

imageView.contentMode = UIViewContentModeScaleAspectFit。也尝试使用 AspectFill。

设置imageView的backgroundColor为clearColor;

于 2012-08-17T12:50:00.033 回答
0
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
    }
}

你可以这样打电话。

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

于 2018-04-23T13:13:56.433 回答