【发布时间】:2012-08-13 21:43:42
【问题描述】:
我有带有 4 个 UIImageViews 的自定义 UITableViewCell。我在 UIImageView.image 中设置了不同大小的图像,但我想按比例缩放(没有黑线顶部/底部和左/右。我该怎么做?
【问题讨论】:
标签: ios image-scaling
我有带有 4 个 UIImageViews 的自定义 UITableViewCell。我在 UIImageView.image 中设置了不同大小的图像,但我想按比例缩放(没有黑线顶部/底部和左/右。我该怎么做?
【问题讨论】:
标签: ios image-scaling
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"))
【讨论】:
您可以使用 contentMode 属性来缩放图像。
如果你想将你的图像放入 imageview 框架中,使其符合其纵横比,请设置
imageView.contentMode = UIViewContentModeScaleAspectFit。也可以尝试使用 AspectFill。
设置imageView的backgroundColor为clearColor;
【讨论】: