• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 将图像大小调整为 Aspect Fit

[复制链接]
菜鸟教程小白 发表于 2022-12-11 18:57:47 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试使用以下流行代码调整图像大小,它正在调整图像大小,但它正在将图像大小调整为 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap