将图像添加到 swift 中另一个 class 的调用函数

adding image to called function from another class in swift

我最近开始使用 swift。我有一个函数可以在一个 swift 文件中调整图像大小,我想在另一个 swift 文件中调用它。这是在 class UIImage:

中添加的函数
public extension UIImage{
class func scalePreservingAspectRatio(targetSize: CGSize) -> UIImage {
        let uimageview = UIImage()
        let widthRatio = targetSize.width / uimageview.size.width
        let heightRatio = targetSize.height / uimageview.size.height
        
        let scaleFactor = min(widthRatio, heightRatio)
        
        let scaledImageSize = CGSize(
            width: uimageview.size.width * scaleFactor,
            height: uimageview.size.height * scaleFactor
        )

        let renderer = UIGraphicsImageRenderer(
            size: scaledImageSize
        )

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

所以当我想在另一个文件中调用这个函数来调整“myimage”的大小时,我想我应该这样写:

let image = UIImage(named: "myimage")
let targetSize = CGSize(width: 100, height: 100)
let scaledImage = image.UIImage.scalePreservingAspectRatio(targetSize: targetSize)

但是通过在 UIImage.scalePreservingAspectRatio() 之前添加 'image',它无法识别函数并显示错误:'UIImage?' 类型的值没有成员 'UIImage' .所以我不知道如何在另一个文件中将我的图像用于此功能。

如果想在UIImage上调用,需要放到扩展中:

extension UIImage {
    func scalePreservingAspectRatio(targetSize: CGSize) -> UIImage {
        ...
    }
}

您可能还希望它能够访问您调用它的图像,因此从函数声明中删除 class。然后你可以这样称呼它:

image.scalePreservingAspectRatio(targetSize: size)

然后更新代码以使用 self 而不是创建新的源图像:

func scalePreservingAspectRatio(targetSize: CGSize) -> UIImage {
    let widthRatio = targetSize.width / size.width
    let heightRatio = targetSize.height / size.height

    let scaleFactor = min(widthRatio, heightRatio)

    let scaledImageSize = CGSize(
        width: size.width * scaleFactor,
        height: size.height * scaleFactor
    )

    let renderer = UIGraphicsImageRenderer(
        size: scaledImageSize
    )

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

    return scaledImage
}