ios - 如何在不造成任何失真的情况下调整 UIImage 的大小和形状?

标签 ios swift xcode uiimage resize

我正在使用 clearbit api 在我的应用程序中获取和显示公司 Logo 。这很好用,只是所有 Logo 的大小都不同,我希望它们都显示为正方形。

有谁知道如何拍摄矩形图像并向其添加给定颜色的额外像素,直到它变成正方形,中间有 Logo ?

This question似乎回答了它,但它已经过时了。我还认为 this question 上的最佳答案会工作,但代码不工作。非常感谢任何帮助,谢谢!

最佳答案

import UIKit

extension UIImage {
    func scalePreservingAspectRatio(targetSize: CGSize) -> UIImage {
        // Determine the scale factor that preserves aspect ratio
        let widthRatio = targetSize.width / size.width
        let heightRatio = targetSize.height / size.height
        
        let scaleFactor = min(widthRatio, heightRatio)
        
        // Compute the new image size that preserves aspect ratio
        let scaledImageSize = CGSize(
            width: size.width * scaleFactor,
            height: size.height * scaleFactor
        )

        // Draw and return the resized UIImage
        let renderer = UIGraphicsImageRenderer(
            size: scaledImageSize
        )

        let scaledImage = renderer.image { _ in
            self.draw(in: CGRect(
                origin: .zero, 
                size: scaledImageSize
            ))
        }
        
        return scaledImage
    }
}

关于ios - 如何在不造成任何失真的情况下调整 UIImage 的大小和形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70982018/

相关文章:

android - ionic 应用程序在 Windows 上运行但不能在 mac 上使用 ios 模拟器运行

ios - 在iOS调整 View 中,当且仅当文本字段隐藏在键盘后面时才应该移动,否则不需要调整。

ios - 如何修改tableviewcell删除-确认按钮的提示字符串

ios - 另一个 UINavigationController 内的 UITabBarController 内的 UINavigationController 的问题

ios - 如何在 SwiftUI 中使用 TabbedView?

ios - SKSpriteNode 在碰撞时失去速度

ios - 当应用程序名称在 InfoPlist.strings 中本地化时,不同的应用程序名称取决于配置

swift - 自定义我的标签栏高度使用外部类?

IOS Swift 处理全局事件

ios - 使用某些 token 发送后,Apple 推送通知无法在生产环境中运行