In my project I was using AlamofireImage in swift. Now we replaced AlamofireImage with the KingFisher library. I have created a struct using below to fit the filter
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)
}
}
}
When we are using AlmofireImage using the below code to set image url
imageView.af.setImage(withURL: imageURL.mediaURL(), placeholderImage: #imageLiteral(resourceName: "icMissingEntreeGrid"), filter: AspectScaledToFitAndCenterSizeFilter(size: imageSize))
Now I replace the code with
imageView.kf.setImage(with: imageURL.mediaURL(), placeholder: imageLiteral(resourceName: "icMissingEntreeGrid"))
But how to add that “AspectScaledToFitAndCenterSizeFilter(size: imageSize)” using KingFisher library. Could anyone please help me out here. Thanks in advance.
To create Kingfisher image processor you need to implement ImageProcessor
protocol:
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)
}
}
}
Usage:
imageView.kf.setImage(
with: imageURL.mediaURL(),
placeholder: #imageLiteral(resourceName: "icMissingEntreeGrid"),
options: [
.processor(AspectScaledToFitAndCenterSizeFilter(size: .zero))
]
)
Check out more processor usages in documentation.