ImageFilter.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // ImageFilter.swift
  2. //
  3. // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. #if os(iOS) || os(tvOS) || os(watchOS)
  24. import UIKit
  25. #elseif os(OSX)
  26. import Cocoa
  27. #endif
  28. // MARK: ImageFilter
  29. /// The `ImageFilter` protocol defines properties for filtering an image as well as identification of the filter.
  30. public protocol ImageFilter {
  31. /// A closure used to create an alternative representation of the given image.
  32. var filter: Image -> Image { get }
  33. /// The string used to uniquely identify the filter operation.
  34. var identifier: String { get }
  35. }
  36. extension ImageFilter {
  37. /// The unique identifier for any `ImageFilter` type.
  38. public var identifier: String { return "\(self.dynamicType)" }
  39. }
  40. // MARK: - Sizable
  41. /// The `Sizable` protocol defines a size property intended for use with `ImageFilter` types.
  42. public protocol Sizable {
  43. /// The size of the type.
  44. var size: CGSize { get }
  45. }
  46. extension ImageFilter where Self: Sizable {
  47. /// The unique idenitifier for an `ImageFilter` conforming to the `Sizable` protocol.
  48. public var identifier: String {
  49. let width = Int64(round(size.width))
  50. let height = Int64(round(size.height))
  51. return "\(self.dynamicType)-size:(\(width)x\(height))"
  52. }
  53. }
  54. // MARK: - Roundable
  55. /// The `Roundable` protocol defines a radius property intended for use with `ImageFilter` types.
  56. public protocol Roundable {
  57. /// The radius of the type.
  58. var radius: CGFloat { get }
  59. }
  60. extension ImageFilter where Self: Roundable {
  61. /// The unique idenitifier for an `ImageFilter` conforming to the `Roundable` protocol.
  62. public var identifier: String {
  63. let radius = Int64(round(self.radius))
  64. return "\(self.dynamicType)-radius:(\(radius))"
  65. }
  66. }
  67. // MARK: - DynamicImageFilter
  68. /// The `DynamicImageFilter` class simplifies custom image filter creation by using a trailing closure initializer.
  69. public struct DynamicImageFilter: ImageFilter {
  70. /// The string used to uniquely identify the image filter operation.
  71. public let identifier: String
  72. /// A closure used to create an alternative representation of the given image.
  73. public let filter: Image -> Image
  74. /**
  75. Initializes the `DynamicImageFilter` instance with the specified identifier and filter closure.
  76. - parameter identifier: The unique identifier of the filter.
  77. - parameter filter: A closure used to create an alternative representation of the given image.
  78. - returns: The new `DynamicImageFilter` instance.
  79. */
  80. public init(_ identifier: String, filter: Image -> Image) {
  81. self.identifier = identifier
  82. self.filter = filter
  83. }
  84. }
  85. // MARK: - CompositeImageFilter
  86. /// The `CompositeImageFilter` protocol defines an additional `filters` property to support multiple composite filters.
  87. public protocol CompositeImageFilter: ImageFilter {
  88. /// The image filters to apply to the image in sequential order.
  89. var filters: [ImageFilter] { get }
  90. }
  91. public extension CompositeImageFilter {
  92. /// The unique idenitifier for any `CompositeImageFilter` type.
  93. var identifier: String {
  94. return filters.map { $0.identifier }.joinWithSeparator("_")
  95. }
  96. /// The filter closure for any `CompositeImageFilter` type.
  97. var filter: Image -> Image {
  98. return { image in
  99. return self.filters.reduce(image) { $1.filter($0) }
  100. }
  101. }
  102. }
  103. // MARK: - DynamicCompositeImageFilter
  104. /// The `DynamicCompositeImageFilter` class is a composite image filter based on a specified array of filters.
  105. public struct DynamicCompositeImageFilter: CompositeImageFilter {
  106. /// The image filters to apply to the image in sequential order.
  107. public let filters: [ImageFilter]
  108. /**
  109. Initializes the `DynamicCompositeImageFilter` instance with the given filters.
  110. - parameter filters: The filters taking part in the composite image filter.
  111. - returns: The new `DynamicCompositeImageFilter` instance.
  112. */
  113. public init(_ filters: [ImageFilter]) {
  114. self.filters = filters
  115. }
  116. /**
  117. Initializes the `DynamicCompositeImageFilter` instance with the given filters.
  118. - parameter filters: The filters taking part in the composite image filter.
  119. - returns: The new `DynamicCompositeImageFilter` instance.
  120. */
  121. public init(_ filters: ImageFilter...) {
  122. self.init(filters)
  123. }
  124. }
  125. #if os(iOS) || os(tvOS) || os(watchOS)
  126. // MARK: - Single Pass Image Filters (iOS, tvOS and watchOS only) -
  127. /// Scales an image to a specified size.
  128. public struct ScaledToSizeFilter: ImageFilter, Sizable {
  129. /// The size of the filter.
  130. public let size: CGSize
  131. /**
  132. Initializes the `ScaledToSizeFilter` instance with the given size.
  133. - parameter size: The size.
  134. - returns: The new `ScaledToSizeFilter` instance.
  135. */
  136. public init(size: CGSize) {
  137. self.size = size
  138. }
  139. /// The filter closure used to create the modified representation of the given image.
  140. public var filter: Image -> Image {
  141. return { image in
  142. return image.af_imageScaledToSize(self.size)
  143. }
  144. }
  145. }
  146. // MARK: -
  147. /// Scales an image from the center while maintaining the aspect ratio to fit within a specified size.
  148. public struct AspectScaledToFitSizeFilter: ImageFilter, Sizable {
  149. /// The size of the filter.
  150. public let size: CGSize
  151. /**
  152. Initializes the `AspectScaledToFitSizeFilter` instance with the given size.
  153. - parameter size: The size.
  154. - returns: The new `AspectScaledToFitSizeFilter` instance.
  155. */
  156. public init(size: CGSize) {
  157. self.size = size
  158. }
  159. /// The filter closure used to create the modified representation of the given image.
  160. public var filter: Image -> Image {
  161. return { image in
  162. return image.af_imageAspectScaledToFitSize(self.size)
  163. }
  164. }
  165. }
  166. // MARK: -
  167. /// Scales an image from the center while maintaining the aspect ratio to fill a specified size. Any pixels that fall
  168. /// outside the specified size are clipped.
  169. public struct AspectScaledToFillSizeFilter: ImageFilter, Sizable {
  170. /// The size of the filter.
  171. public let size: CGSize
  172. /**
  173. Initializes the `AspectScaledToFillSizeFilter` instance with the given size.
  174. - parameter size: The size.
  175. - returns: The new `AspectScaledToFillSizeFilter` instance.
  176. */
  177. public init(size: CGSize) {
  178. self.size = size
  179. }
  180. /// The filter closure used to create the modified representation of the given image.
  181. public var filter: Image -> Image {
  182. return { image in
  183. return image.af_imageAspectScaledToFillSize(self.size)
  184. }
  185. }
  186. }
  187. // MARK: -
  188. /// Rounds the corners of an image to the specified radius.
  189. public struct RoundedCornersFilter: ImageFilter, Roundable {
  190. /// The radius of the filter.
  191. public let radius: CGFloat
  192. /// Whether to divide the radius by the image scale.
  193. public let divideRadiusByImageScale: Bool
  194. /**
  195. Initializes the `RoundedCornersFilter` instance with the given radius.
  196. - parameter radius: The radius.
  197. - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the
  198. image has the same resolution for all screen scales such as @1x, @2x and
  199. @3x (i.e. single image from web server). Set to `false` for images loaded
  200. from an asset catalog with varying resolutions for each screen scale.
  201. `false` by default.
  202. - returns: The new `RoundedCornersFilter` instance.
  203. */
  204. public init(radius: CGFloat, divideRadiusByImageScale: Bool = false) {
  205. self.radius = radius
  206. self.divideRadiusByImageScale = divideRadiusByImageScale
  207. }
  208. /// The filter closure used to create the modified representation of the given image.
  209. public var filter: Image -> Image {
  210. return { image in
  211. return image.af_imageWithRoundedCornerRadius(
  212. self.radius,
  213. divideRadiusByImageScale: self.divideRadiusByImageScale
  214. )
  215. }
  216. }
  217. /// The unique idenitifier for an `ImageFilter` conforming to the `Roundable` protocol.
  218. public var identifier: String {
  219. let radius = Int64(round(self.radius))
  220. return "\(self.dynamicType)-radius:(\(radius))-divided:(\(divideRadiusByImageScale))"
  221. }
  222. }
  223. // MARK: -
  224. /// Rounds the corners of an image into a circle.
  225. public struct CircleFilter: ImageFilter {
  226. /**
  227. Initializes the `CircleFilter` instance.
  228. - returns: The new `CircleFilter` instance.
  229. */
  230. public init() {}
  231. /// The filter closure used to create the modified representation of the given image.
  232. public var filter: Image -> Image {
  233. return { image in
  234. return image.af_imageRoundedIntoCircle()
  235. }
  236. }
  237. }
  238. // MARK: -
  239. #if os(iOS) || os(tvOS)
  240. /// Blurs an image using a `CIGaussianBlur` filter with the specified blur radius.
  241. public struct BlurFilter: ImageFilter {
  242. /// The blur radius of the filter.
  243. let blurRadius: UInt
  244. /**
  245. Initializes the `BlurFilter` instance with the given blur radius.
  246. - parameter blurRadius: The blur radius.
  247. - returns: The new `BlurFilter` instance.
  248. */
  249. public init(blurRadius: UInt = 10) {
  250. self.blurRadius = blurRadius
  251. }
  252. /// The filter closure used to create the modified representation of the given image.
  253. public var filter: Image -> Image {
  254. return { image in
  255. let parameters = ["inputRadius": self.blurRadius]
  256. return image.af_imageWithAppliedCoreImageFilter("CIGaussianBlur", filterParameters: parameters) ?? image
  257. }
  258. }
  259. }
  260. #endif
  261. // MARK: - Composite Image Filters (iOS, tvOS and watchOS only) -
  262. /// Scales an image to a specified size, then rounds the corners to the specified radius.
  263. public struct ScaledToSizeWithRoundedCornersFilter: CompositeImageFilter {
  264. /**
  265. Initializes the `ScaledToSizeWithRoundedCornersFilter` instance with the given size and radius.
  266. - parameter size: The size.
  267. - parameter radius: The radius.
  268. - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the
  269. image has the same resolution for all screen scales such as @1x, @2x and
  270. @3x (i.e. single image from web server). Set to `false` for images loaded
  271. from an asset catalog with varying resolutions for each screen scale.
  272. `false` by default.
  273. - returns: The new `ScaledToSizeWithRoundedCornersFilter` instance.
  274. */
  275. public init(size: CGSize, radius: CGFloat, divideRadiusByImageScale: Bool = false) {
  276. self.filters = [
  277. ScaledToSizeFilter(size: size),
  278. RoundedCornersFilter(radius: radius, divideRadiusByImageScale: divideRadiusByImageScale)
  279. ]
  280. }
  281. /// The image filters to apply to the image in sequential order.
  282. public let filters: [ImageFilter]
  283. }
  284. // MARK: -
  285. /// Scales an image from the center while maintaining the aspect ratio to fit within a specified size, then rounds the
  286. /// corners to the specified radius.
  287. public struct AspectScaledToFillSizeWithRoundedCornersFilter: CompositeImageFilter {
  288. /**
  289. Initializes the `AspectScaledToFillSizeWithRoundedCornersFilter` instance with the given size and radius.
  290. - parameter size: The size.
  291. - parameter radius: The radius.
  292. - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the
  293. image has the same resolution for all screen scales such as @1x, @2x and
  294. @3x (i.e. single image from web server). Set to `false` for images loaded
  295. from an asset catalog with varying resolutions for each screen scale.
  296. `false` by default.
  297. - returns: The new `AspectScaledToFillSizeWithRoundedCornersFilter` instance.
  298. */
  299. public init(size: CGSize, radius: CGFloat, divideRadiusByImageScale: Bool = false) {
  300. self.filters = [
  301. AspectScaledToFillSizeFilter(size: size),
  302. RoundedCornersFilter(radius: radius, divideRadiusByImageScale: divideRadiusByImageScale)
  303. ]
  304. }
  305. /// The image filters to apply to the image in sequential order.
  306. public let filters: [ImageFilter]
  307. }
  308. // MARK: -
  309. /// Scales an image to a specified size, then rounds the corners into a circle.
  310. public struct ScaledToSizeCircleFilter: CompositeImageFilter {
  311. /**
  312. Initializes the `ScaledToSizeCircleFilter` instance with the given size.
  313. - parameter size: The size.
  314. - returns: The new `ScaledToSizeCircleFilter` instance.
  315. */
  316. public init(size: CGSize) {
  317. self.filters = [ScaledToSizeFilter(size: size), CircleFilter()]
  318. }
  319. /// The image filters to apply to the image in sequential order.
  320. public let filters: [ImageFilter]
  321. }
  322. // MARK: -
  323. /// Scales an image from the center while maintaining the aspect ratio to fit within a specified size, then rounds the
  324. /// corners into a circle.
  325. public struct AspectScaledToFillSizeCircleFilter: CompositeImageFilter {
  326. /**
  327. Initializes the `AspectScaledToFillSizeCircleFilter` instance with the given size.
  328. - parameter size: The size.
  329. - returns: The new `AspectScaledToFillSizeCircleFilter` instance.
  330. */
  331. public init(size: CGSize) {
  332. self.filters = [AspectScaledToFillSizeFilter(size: size), CircleFilter()]
  333. }
  334. /// The image filters to apply to the image in sequential order.
  335. public let filters: [ImageFilter]
  336. }
  337. #endif