Browse Source

add ImageModifier

Ethan Gill 8 years ago
parent
commit
bff776d8f7

+ 10 - 0
Kingfisher.xcodeproj/project.pbxproj

@@ -335,6 +335,10 @@
 		D9638BA61C7DC71F0046523D /* ImagePrefetcherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9638BA41C7DC71F0046523D /* ImagePrefetcherTests.swift */; };
 		D9638BA71C7DCF560046523D /* ImagePrefetcherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9638BA41C7DC71F0046523D /* ImagePrefetcherTests.swift */; };
 		D9638BA81C7DCF570046523D /* ImagePrefetcherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9638BA41C7DC71F0046523D /* ImagePrefetcherTests.swift */; };
+		F78F5EBD1FCDDE42001A9111 /* ImageModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = F78F5EBC1FCDDE42001A9111 /* ImageModifier.swift */; };
+		F78F5EBE1FCDDE42001A9111 /* ImageModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = F78F5EBC1FCDDE42001A9111 /* ImageModifier.swift */; };
+		F78F5EBF1FCDDE42001A9111 /* ImageModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = F78F5EBC1FCDDE42001A9111 /* ImageModifier.swift */; };
+		F78F5EC01FCDDE42001A9111 /* ImageModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = F78F5EBC1FCDDE42001A9111 /* ImageModifier.swift */; };
 		FB402D0E1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB402D0D1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift */; };
 		FB402D0F1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB402D0D1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift */; };
 		FB402D101EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB402D0D1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift */; };
@@ -660,6 +664,7 @@
 		D9638B9F1C7DBA660046523D /* ImagePrefetcher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ImagePrefetcher.swift; path = Sources/ImagePrefetcher.swift; sourceTree = "<group>"; };
 		D9638BA41C7DC71F0046523D /* ImagePrefetcherTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImagePrefetcherTests.swift; sourceTree = "<group>"; };
 		DE80CB18FBC9F9F23DC1FDCF /* Pods-KingfisherTests-macOS.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-KingfisherTests-macOS.release.xcconfig"; path = "Pods/Target Support Files/Pods-KingfisherTests-macOS/Pods-KingfisherTests-macOS.release.xcconfig"; sourceTree = "<group>"; };
+		F78F5EBC1FCDDE42001A9111 /* ImageModifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ImageModifier.swift; path = Sources/ImageModifier.swift; sourceTree = "<group>"; };
 		FB402D0D1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = FormatIndicatedCacheSerializer.swift; path = Sources/FormatIndicatedCacheSerializer.swift; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
@@ -987,6 +992,7 @@
 				D10945EC1C526B6C001408EB /* ImageDownloader.swift */,
 				D9638B9F1C7DBA660046523D /* ImagePrefetcher.swift */,
 				4B2B8E491D70128200FC4749 /* ImageProcessor.swift */,
+				F78F5EBC1FCDDE42001A9111 /* ImageModifier.swift */,
 				4BB24C3C1D79215A00CD5F9C /* CacheSerializer.swift */,
 				FB402D0D1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift */,
 				4BFBEE7C1D7D0C3600699FD3 /* RequestModifier.swift */,
@@ -2150,6 +2156,7 @@
 				D109461B1C526C61001408EB /* ImageCache.swift in Sources */,
 				D109461C1C526C61001408EB /* ImageDownloader.swift in Sources */,
 				D109461D1C526C61001408EB /* ImageTransition.swift in Sources */,
+				F78F5EBF1FCDDE42001A9111 /* ImageModifier.swift in Sources */,
 				4B2B8E4C1D70141000FC4749 /* ImageProcessor.swift in Sources */,
 				4BFBEE7F1D7D0C3600699FD3 /* RequestModifier.swift in Sources */,
 				4B7742411D87E08A0077024E /* Indicator.swift in Sources */,
@@ -2249,6 +2256,7 @@
 				4BB24C3E1D79215A00CD5F9C /* CacheSerializer.swift in Sources */,
 				D10946171C526C0D001408EB /* ThreadHelper.swift in Sources */,
 				444C03EA1F548F6200990BCC /* Placeholder.swift in Sources */,
+				F78F5EBE1FCDDE42001A9111 /* ImageModifier.swift in Sources */,
 				FB402D0F1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift in Sources */,
 				D10946181C526C0D001408EB /* UIButton+Kingfisher.swift in Sources */,
 			);
@@ -2258,6 +2266,7 @@
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
+				F78F5EC01FCDDE42001A9111 /* ImageModifier.swift in Sources */,
 				D109462D1C526CF5001408EB /* ImageTransition.swift in Sources */,
 				FB402D111EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift in Sources */,
 				4B2B8E4D1D70141100FC4749 /* ImageProcessor.swift in Sources */,
@@ -2319,6 +2328,7 @@
 				4BB24C3D1D79215A00CD5F9C /* CacheSerializer.swift in Sources */,
 				D10946001C526B86001408EB /* ThreadHelper.swift in Sources */,
 				444C03E91F548F6100990BCC /* Placeholder.swift in Sources */,
+				F78F5EBD1FCDDE42001A9111 /* ImageModifier.swift in Sources */,
 				FB402D0E1EDEAB7E002B62A1 /* FormatIndicatedCacheSerializer.swift in Sources */,
 				D10946011C526B86001408EB /* UIButton+Kingfisher.swift in Sources */,
 			);

+ 187 - 0
Sources/ImageModifier.swift

@@ -0,0 +1,187 @@
+//
+//  ImageModifier.swift
+//  Kingfisher
+//
+//  Created by Ethan Gill on 2017/11/28.
+//
+//  Copyright (c) 2017 Ethan Gill <ethan.gill@me.com>
+//
+//  Permission is hereby granted, free of charge, to any person obtaining a copy
+//  of this software and associated documentation files (the "Software"), to deal
+//  in the Software without restriction, including without limitation the rights
+//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+//  copies of the Software, and to permit persons to whom the Software is
+//  furnished to do so, subject to the following conditions:
+//
+//  The above copyright notice and this permission notice shall be included in
+//  all copies or substantial portions of the Software.
+//
+//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+//  THE SOFTWARE.
+
+import Foundation
+
+/// An `ImageModifier` can be used to change properties on an Image in between
+/// cache serialization and use of the image.
+public protocol ImageModifier {
+    /// Identifier of the modifier. It will be used to identify the modifier when
+    /// modifying an image.
+    ///
+    /// - Note: Do not supply an empty string for a customized modifier, as the
+    /// `DefaultImageModifier` uses this idenfifier. It is recommended to use a
+    /// reverse domain name notation string of your own for the identifier.
+    var identifier: String { get }
+
+    /// Modify an input `Image`.
+    ///
+    /// - parameter image:   Image which will be modified by `self`
+    /// - parameter options: Options when modifying the image.
+    ///
+    /// - returns: The modified image.
+    ///
+    /// - Note: The return value will be unmodified if modifying is not possible on
+    ///         the current platform.
+    /// - Note: Most modifiers support UIImage or NSImage, but not CGImage.
+    func modify(image: Image, options: KingfisherOptionsInfo) -> Image?
+}
+
+typealias ModifierImp = ((Image, KingfisherOptionsInfo) -> Image?)
+
+public extension ImageModifier {
+
+    /// Append an `ImageModifier` to another. The identifier of the new `ImageModifier`
+    /// will be "\(self.identifier)|>\(another.identifier)".
+    ///
+    /// - parameter another: An `ImageModifier` you want to append to `self`.
+    ///
+    /// - returns: The new `ImageModifier` will process the image in the order
+    ///            of the two modifiers concatenated.
+    public func append(another: ImageModifier) -> ImageModifier {
+        let newIdentifier = identifier.appending("|>\(another.identifier)")
+        return GeneralModifier(identifier: newIdentifier) {
+            image, options in
+            if let image = self.modify(image: image, options: options) {
+                return another.modify(image: image, options: options)
+            } else {
+                return nil
+            }
+        }
+    }
+}
+
+func ==(left: ImageModifier, right: ImageModifier) -> Bool {
+    return left.identifier == right.identifier
+}
+
+func !=(left: ImageModifier, right: ImageModifier) -> Bool {
+    return !(left == right)
+}
+
+fileprivate struct GeneralModifier: ImageModifier {
+    let identifier: String
+    let m: ModifierImp
+    func modify(image: Image, options: KingfisherOptionsInfo) -> Image? {
+        return m(image, options)
+    }
+}
+
+/// The default modifier.
+/// Does nothing and returns the image it was given
+public struct DefaultImageModifier: ImageModifier {
+
+    /// A default `DefaultImageModifier` which can be used everywhere.
+    public static let `default` = DefaultImageModifier()
+
+    /// Identifier of the modifier.
+    /// - Note: See documentation of `ImageModifier` protocol for more.
+    public let identifier = ""
+
+    /// Initialize a `DefaultImageModifier`
+    public init() {}
+
+    /// Modify an input `Image`.
+    ///
+    /// - parameter image:   Image which will be modified by `self`
+    /// - parameter options: Options when modifying the image.
+    ///
+    /// - returns: The modified image.
+    ///
+    /// - Note: See documentation of `ImageModifier` protocol for more.
+    public func modify(image: Image, options: KingfisherOptionsInfo) -> Image? {
+        return image
+    }
+}
+
+#if os(iOS) || os(tvOS) || os(watchOS)
+import UIKit
+
+/// Modifier for setting the rendering mode of images.
+/// Only UI-based images are supported; if a non-UI image is passed in, the modifier
+/// will do nothing.
+public struct RenderingModeImageModifier: ImageModifier {
+
+    /// Identifier of the modifier.
+    /// - Note: See documentation of `ImageModifier` protocol for more.
+    public let identifier: String
+
+    /// The rendering mode to apply to the image.
+    public let renderingMode: UIImageRenderingMode
+
+    /// Initialize a `RenderingModeImageModifier`
+    ///
+    /// - parameter renderingMode: The rendering mode to apply to the image.
+    ///                            Default is .automatic
+    public init(renderingMode: UIImageRenderingMode = .automatic) {
+        self.renderingMode = renderingMode
+        self.identifier = "com.onevcat.Kingfisher.RenderingModeImageModifier(\(renderingMode))"
+    }
+
+    /// Modify an input `Image`.
+    ///
+    /// - parameter image:   Image which will be modified by `self`
+    /// - parameter options: Options when modifying the image.
+    ///
+    /// - returns: The modified image.
+    ///
+    /// - Note: See documentation of `ImageModifier` protocol for more.
+    public func modify(image: Image, options: KingfisherOptionsInfo) -> Image? {
+        return image.withRenderingMode(renderingMode)
+    }
+}
+
+public struct FlipsForRightToLeftLayoutDirectionImageModifier: ImageModifier {
+    /// Identifier of the modifier.
+    /// - Note: See documentation of `ImageModifier` protocol for more.
+    public let identifier: String
+
+    /// Initialize a `FlipsForRightToLeftLayoutDirectionImageModifier`
+    ///
+    /// - Note: On versions of iOS lower than 9.0, the image will be returned
+    ///         unmodified.
+    public init() {
+        self.identifier = "com.onevcat.Kingfisher.FlipsForRightToLeftLayoutDirectionImageModifier"
+    }
+
+    /// Modify an input `Image`.
+    ///
+    /// - parameter image:   Image which will be modified by `self`
+    /// - parameter options: Options when modifying the image.
+    ///
+    /// - returns: The modified image.
+    ///
+    /// - Note: See documentation of `ImageModifier` protocol for more.
+    public func modify(image: Image, options: KingfisherOptionsInfo) -> Image? {
+        if #available(iOS 9.0, *) {
+            return image.imageFlippedForRightToLeftLayoutDirection()
+        } else {
+            return image
+        }
+    }
+}
+
+#endif

+ 1 - 1
Sources/ImageProcessor.swift

@@ -39,7 +39,7 @@ public enum ImageProcessItem {
 /// An `ImageProcessor` would be used to convert some downloaded data to an image.
 public protocol ImageProcessor {
     /// Identifier of the processor. It will be used to identify the processor when 
-    /// caching and retriving an image. You might want to make sure that processors with
+    /// caching and retrieving an image. You might want to make sure that processors with
     /// same properties/functionality have the same identifiers, so correct processed images
     /// could be retrived with proper key.
     /// 

+ 21 - 1
Sources/KingfisherOptionsInfo.swift

@@ -109,7 +109,7 @@ public enum KingfisherOptionsInfoItem {
     case requestModifier(ImageDownloadRequestModifier)
     
     /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image
-    /// and/or apply some filter on it. If a cache is connected to the downloader (it happenes when you are using
+    /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using
     /// KingfisherManager or the image extension methods), the converted image will also be sent to cache as well as the
     /// image view. `DefaultImageProcessor.default` will be used by default.
     case processor(ImageProcessor)
@@ -118,6 +118,15 @@ public enum KingfisherOptionsInfoItem {
     /// retrieving from disk cache or vice versa for storing to disk cache.
     /// `DefaultCacheSerializer.default` will be used by default.
     case cacheSerializer(CacheSerializer)
+
+    /// Modifier for modifying an image right before it is used.
+    /// If the image was fetched directly from the downloader, the modifier will
+    /// run directly after the processor.
+    /// If the image is being fetched from a cache, the modifier will run after
+    /// the cacheSerializer.
+    /// Use `ImageModifier` when you need to set properties on a concrete type
+    /// of `Image`, such as a `UIImage`, that do not persist when caching the image.
+    case imageModifier(ImageModifier)
     
     /// Keep the existing image while setting another image to an image view.
     /// By setting this option, the placeholder image parameter of imageview extension method
@@ -164,6 +173,7 @@ func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Boo
     case (.requestModifier(_), .requestModifier(_)): return true
     case (.processor(_), .processor(_)): return true
     case (.cacheSerializer(_), .cacheSerializer(_)): return true
+    case (.imageModifier(_), .imageModifier(_)): return true
     case (.keepCurrentImageWhileLoading, .keepCurrentImageWhileLoading): return true
     case (.onlyLoadFirstFrame, .onlyLoadFirstFrame): return true
     case (.cacheOriginalImage, .cacheOriginalImage): return true
@@ -308,6 +318,16 @@ public extension Collection where Iterator.Element == KingfisherOptionsInfoItem
         }
         return DefaultImageProcessor.default
     }
+
+    /// `ImageModifier` for modifying right before the image is displayed.
+    public var imageModifier: ImageModifier {
+        if let item = lastMatchIgnoringAssociatedValue(.imageModifier(DefaultImageModifier.default)),
+            case .imageModifier(let imageModifier) = item
+        {
+            return imageModifier
+        }
+        return DefaultImageModifier.default
+    }
     
     /// `CacheSerializer` to convert image to data for storing in cache.
     public var cacheSerializer: CacheSerializer {