我正在使用 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/