OGeek|极客世界-中国程序员成长平台

标题: ios - 将图像大小调整为 Aspect Fit [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:57
标题: ios - 将图像大小调整为 Aspect Fit

我正在尝试使用以下流行代码调整图像大小,它正在调整图像大小,但它正在将图像大小调整为 Scale to Fill,我想将它们调整为 Aspect Fit . 我该怎么做?

func resizeImage(image: UIImage, newSize: CGSize) -> (UIImage) {

    let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral
    UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
    let context = UIGraphicsGetCurrentContext()

    // Set the quality level to use when rescaling
    context!.interpolationQuality = CGInterpolationQuality.default
    let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height )
    context!.concatenate(flipVertical)

    // Draw into the context; this scales the image
    context?.draw(image.cgImage!, in: CGRect(x: 0.0,y: 0.0, width: newRect.width, height: newRect.height))

    let newImageRef = context!.makeImage()! as CGImage
    let newImage = UIImage(cgImage: newImageRef)

    // Get the resized image from the context and a UIImage
    UIGraphicsEndImageContext()

    return newImage
}

我已经将图片的内容模式设置为Aspect Fit,但还是不行。

这就是我在 Collection View Controller 中调用上述代码的方式

 cell.imageView.image =  UIImage(named: dogImages[indexPath.row])?.resizeImage(image: UIImage(named: dogImages[indexPath.row])

我在 Storyboard 中手动选择了我的图像并将其内容模式设置为 apsect fit



Best Answer-推荐答案


您是否尝试将 newSize 设置为原始图像大小的纵横比。如果要固定宽度,则按宽度计算高度,如果要固定高度,则按高度计算宽度

当宽度固定时计算高度:

    let fixedWidth: CGFloat = 200
    let newHeight = fixedWidth * image.size.height / image.size.width
    let convertedImage = resizeImage(image: image, newSize: CGSize(width: fixedWidth, height: newHeight))

在固定高度时计算宽度:

    let fixedheight: CGFloat = 200
    let newWidth = fixedheight * image.size.width / image.size.height
    let convertedImage = resizeImage(image: image, newSize: CGSize(width: newWidth, height: fixedheight))

您可以使用此调整后的图像与宽高比。

还可以查看答案:https://stackoverflow.com/a/8858464/2677551 ,这可能会有所帮助

关于ios - 将图像大小调整为 Aspect Fit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46678242/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4