首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在swift中使用kingFisher库中的AspectScaledToFitAndCenterSizeFilter

如何在swift中使用kingFisher库中的AspectScaledToFitAndCenterSizeFilter
EN

Stack Overflow用户
提问于 2021-09-22 10:51:06
回答 1查看 28关注 0票数 1

在我的项目中,我使用了swift中的AlamofireImage。现在,我们用KingFisher库替换了AlamofireImage。我已经使用下面的方法创建了一个结构来适应过滤器

代码语言:javascript
复制
struct AspectScaledToFitAndCenterSizeFilter: ImageFilter, Sizable {
    /// The size of the filter.
    let size: CGSize

    /// Initializes the `AspectScaledToFitSizeFilter` instance with the given size.
    ///
    /// - parameter size: The size.
    ///
    /// - returns: The new `AspectScaledToFitSizeFilter` instance.
    init(size: CGSize) {
        self.size = size
    }

    /// The filter closure used to create the modified representation of the given image.
    var filter: (UIImage) -> UIImage {
        { image in
            image.imageAspectScaledAndCenter(toFit: self.size)
        }
    }
} 

当我们使用AlmofireImage时,使用下面的代码来设置图像url

代码语言:javascript
复制
imageView.af.setImage(withURL: imageURL.mediaURL(), placeholderImage: #imageLiteral(resourceName: "icMissingEntreeGrid"), filter: AspectScaledToFitAndCenterSizeFilter(size: imageSize))

现在我将代码替换为

代码语言:javascript
复制
imageView.kf.setImage(with: imageURL.mediaURL(), placeholder:  imageLiteral(resourceName: "icMissingEntreeGrid"))

而是如何使用KingFisher库添加“AspectScaledToFitAndCenterSizeFilter(size:imageSize)”。有谁能帮帮我吗。提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-22 16:57:24

要创建翠鸟图像处理器,需要实现ImageProcessor协议:

代码语言:javascript
复制
class AspectScaledToFitAndCenterSizeFilter: ImageProcessor {
    /// Identifier of the processor.
    /// - Note: See documentation of `ImageProcessor` protocol for more.
    let identifier: String

    /// The size of the filter.
    let size: CGSize

    /// Initializes the `AspectScaledToFitSizeFilter` instance with the given size.
    ///
    /// - parameter size: The size.
    ///
    /// - returns: The new `AspectScaledToFitSizeFilter` instance.
    init(size: CGSize) {
        self.size = size
        identifier = "com.package.AspectScaledToFitAndCenterSizeFilter(\(size))"
    }

    func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
        switch item {
        case .image(let image):
            return image.imageAspectScaledAndCenter(toFit: self.size)
        case .data:
            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
        }
    }
}

用法:

代码语言:javascript
复制
imageView.kf.setImage(
    with: imageURL.mediaURL(),
    placeholder: #imageLiteral(resourceName: "icMissingEntreeGrid"),
    options: [
        .processor(AspectScaledToFitAndCenterSizeFilter(size: .zero))
    ]
)

documentation中查看更多处理器使用情况。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69282769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档