5 // Created by Wei Wang on 16/1/6.
7 // Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 private var imagesKey: Void?
31 private var durationKey: Void?
34 import MobileCoreServices
35 private var imageSourceKey: Void?
37 private var animatedImageDataKey: Void?
47 // MARK: - Image Properties
48 extension Kingfisher where Base: Image {
49 fileprivate(set) var animatedImageData: Data? {
51 return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data
54 objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
59 var cgImage: CGImage? {
60 return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
67 fileprivate(set) var images: [Image]? {
69 return objc_getAssociatedObject(base, &imagesKey) as? [Image]
72 objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
76 fileprivate(set) var duration: TimeInterval {
78 return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0
81 objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
86 return base.representations.reduce(CGSize.zero, { size, rep in
87 return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh)))
92 var cgImage: CGImage? {
100 var images: [Image]? {
104 var duration: TimeInterval {
108 fileprivate(set) var imageSource: ImageSource? {
110 return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource
113 objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
123 // MARK: - Image Conversion
124 extension Kingfisher where Base: Image {
126 static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
127 return Image(cgImage: cgImage, size: CGSize.zero)
131 Normalize the image. This method does nothing in OS X.
133 - returns: The image itself.
135 public var normalized: Image {
139 static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? {
143 static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
144 if let refImage = refImage {
145 return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
147 return Image(cgImage: cgImage, scale: scale, orientation: .up)
152 Normalize the image. This method will try to redraw an image with orientation and scale considered.
154 - returns: The normalized image with orientation set to up and correct scale.
156 public var normalized: Image {
157 // prevent animated image (GIF) lose it's images
158 guard images == nil else { return base }
159 // No need to do anything if already up
160 guard base.imageOrientation != .up else { return base }
162 return draw(cgImage: nil, to: size) {
163 base.draw(in: CGRect(origin: CGPoint.zero, size: size))
167 static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? {
168 return .animatedImage(with: images, duration: duration)
173 // MARK: - Image Representation
174 extension Kingfisher where Base: Image {
176 public func pngRepresentation() -> Data? {
178 guard let cgimage = cgImage else {
181 let rep = NSBitmapImageRep(cgImage: cgimage)
182 return rep.representation(using: .png, properties: [:])
184 return UIImagePNGRepresentation(base)
189 public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
191 guard let cgImage = cgImage else {
194 let rep = NSBitmapImageRep(cgImage: cgImage)
195 return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
197 return UIImageJPEGRepresentation(base, compressionQuality)
202 public func gifRepresentation() -> Data? {
203 return animatedImageData
207 // MARK: - Create images from data
208 extension Kingfisher where Base: Image {
209 static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? {
211 func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
213 //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
214 func frameDuration(from gifInfo: NSDictionary?) -> Double {
215 let gifDefaultFrameDuration = 0.100
217 guard let gifInfo = gifInfo else {
218 return gifDefaultFrameDuration
221 let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
222 let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
223 let duration = unclampedDelayTime ?? delayTime
225 guard let frameDuration = duration else { return gifDefaultFrameDuration }
227 return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
230 let frameCount = CGImageSourceGetCount(imageSource)
231 var images = [Image]()
232 var gifDuration = 0.0
233 for i in 0 ..< frameCount {
235 guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
241 gifDuration = Double.infinity
245 guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else {
249 let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary
250 gifDuration += frameDuration(from: gifInfo)
253 images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil))
255 if onlyFirstFrame { break }
258 return (images, gifDuration)
261 // Start of kf.animatedImageWithGIFData
262 let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
263 guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
268 guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
275 image = Image(data: data)
276 image?.kf.images = images
277 image?.kf.duration = gifDuration
279 image?.kf.animatedImageData = data
284 if preloadAll || onlyFirstFrame {
285 guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil }
286 image = onlyFirstFrame ? images.first : Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
288 image = Image(data: data)
289 image?.kf.imageSource = ImageSource(ref: imageSource)
291 image?.kf.animatedImageData = data
296 static func image(data: Data, scale: CGFloat, preloadAllAnimationData: Bool, onlyFirstFrame: Bool) -> Image? {
300 switch data.kf.imageFormat {
302 image = Image(data: data)
304 image = Image(data: data)
306 image = Kingfisher<Image>.animated(
310 preloadAll: preloadAllAnimationData,
311 onlyFirstFrame: onlyFirstFrame)
313 image = Image(data: data)
316 switch data.kf.imageFormat {
318 image = Image(data: data, scale: scale)
320 image = Image(data: data, scale: scale)
322 image = Kingfisher<Image>.animated(
326 preloadAll: preloadAllAnimationData,
327 onlyFirstFrame: onlyFirstFrame)
329 image = Image(data: data, scale: scale)
337 // MARK: - Image Transforming
338 extension Kingfisher where Base: Image {
339 // MARK: - Blend Mode
340 /// Create image based on `self` and apply blend mode.
342 /// - parameter blendMode: The blend mode of creating image.
343 /// - parameter alpha: The alpha should be used for image.
344 /// - parameter backgroundColor: The background color for the output image.
346 /// - returns: An image with blend mode applied.
348 /// - Note: This method only works for CG-based image.
350 public func image(withBlendMode blendMode: CGBlendMode,
351 alpha: CGFloat = 1.0,
352 backgroundColor: Color? = nil) -> Image
354 guard let cgImage = cgImage else {
355 assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
359 let rect = CGRect(origin: .zero, size: size)
360 return draw(cgImage: cgImage, to: rect.size) {
361 if let backgroundColor = backgroundColor {
362 backgroundColor.setFill()
366 base.draw(in: rect, blendMode: blendMode, alpha: alpha)
371 // MARK: - Compositing Operation
372 /// Create image based on `self` and apply compositing operation.
374 /// - parameter compositingOperation: The compositing operation of creating image.
375 /// - parameter alpha: The alpha should be used for image.
376 /// - parameter backgroundColor: The background color for the output image.
378 /// - returns: An image with compositing operation applied.
380 /// - Note: This method only works for CG-based image.
382 public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
383 alpha: CGFloat = 1.0,
384 backgroundColor: Color? = nil) -> Image
386 guard let cgImage = cgImage else {
387 assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
391 let rect = CGRect(origin: .zero, size: size)
392 return draw(cgImage: cgImage, to: rect.size) {
393 if let backgroundColor = backgroundColor {
394 backgroundColor.setFill()
398 base.draw(in: rect, from: NSRect.zero, operation: compositingOperation, fraction: alpha)
403 // MARK: - Round Corner
404 /// Create a round corner image based on `self`.
406 /// - parameter radius: The round corner radius of creating image.
407 /// - parameter size: The target size of creating image.
408 /// - parameter corners: The target corners which will be applied rounding.
409 /// - parameter backgroundColor: The background color for the output image
411 /// - returns: An image with round corner of `self`.
413 /// - Note: This method only works for CG-based image.
414 public func image(withRoundRadius radius: CGFloat,
416 roundingCorners corners: RectCorner = .all,
417 backgroundColor: Color? = nil) -> Image
419 guard let cgImage = cgImage else {
420 assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
424 let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
425 return draw(cgImage: cgImage, to: size) {
427 if let backgroundColor = backgroundColor {
428 let rectPath = NSBezierPath(rect: rect)
429 backgroundColor.setFill()
433 let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
434 path.windingRule = .evenOddWindingRule
438 guard let context = UIGraphicsGetCurrentContext() else {
439 assertionFailure("[Kingfisher] Failed to create CG context for image.")
443 if let backgroundColor = backgroundColor {
444 let rectPath = UIBezierPath(rect: rect)
445 backgroundColor.setFill()
449 let path = UIBezierPath(roundedRect: rect,
450 byRoundingCorners: corners.uiRectCorner,
451 cornerRadii: CGSize(width: radius, height: radius)).cgPath
452 context.addPath(path)
459 #if os(iOS) || os(tvOS)
460 func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
462 case .scaleAspectFit:
463 return resize(to: size, for: .aspectFit)
464 case .scaleAspectFill:
465 return resize(to: size, for: .aspectFill)
467 return resize(to: size)
473 /// Resize `self` to an image of new size.
475 /// - parameter size: The target size.
477 /// - returns: An image with new size.
479 /// - Note: This method only works for CG-based image.
480 public func resize(to size: CGSize) -> Image {
482 guard let cgImage = cgImage else {
483 assertionFailure("[Kingfisher] Resize only works for CG-based image.")
487 let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
488 return draw(cgImage: cgImage, to: size) {
490 base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
497 /// Resize `self` to an image of new size, respecting the content mode.
500 /// - size: The target size.
501 /// - contentMode: Content mode of output image should be.
502 /// - Returns: An image with new size.
503 public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
506 let newSize = self.size.kf.constrained(size)
507 return resize(to: newSize)
509 let newSize = self.size.kf.filling(size)
510 return resize(to: newSize)
512 return resize(to: size)
516 public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
517 guard let cgImage = cgImage else {
518 assertionFailure("[Kingfisher] Crop only works for CG-based image.")
522 let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
523 guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
524 assertionFailure("[Kingfisher] Cropping image failed.")
528 return Kingfisher.image(cgImage: image, scale: scale, refImage: base)
533 /// Create an image with blur effect based on `self`.
535 /// - parameter radius: The blur radius should be used when creating blur effect.
537 /// - returns: An image with blur effect applied.
539 /// - Note: This method only works for CG-based image.
540 public func blurred(withRadius radius: CGFloat) -> Image {
544 guard let cgImage = cgImage else {
545 assertionFailure("[Kingfisher] Blur only works for CG-based image.")
549 // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
550 // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
551 // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
552 let s = Float(max(radius, 2.0))
553 // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
555 // Fix the slow compiling time for Swift 3.
556 // See https://github.com/onevcat/Kingfisher/issues/611
557 let pi2 = 2 * Float.pi
558 let sqrtPi2 = sqrt(pi2)
559 var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
561 if targetRadius.isEven {
568 } else if radius < 1.5 {
574 let w = Int(size.width)
575 let h = Int(size.height)
576 let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
578 func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
579 let data = context.data
580 let width = vImagePixelCount(context.width)
581 let height = vImagePixelCount(context.height)
582 let rowBytes = context.bytesPerRow
584 return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
587 guard let context = beginContext(size: size, scale: scale) else {
588 assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
591 defer { endContext() }
593 context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
595 var inBuffer = createEffectBuffer(context)
597 guard let outContext = beginContext(size: size, scale: scale) else {
598 assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
601 defer { endContext() }
602 var outBuffer = createEffectBuffer(outContext)
604 for _ in 0 ..< iterations {
605 vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
606 (inBuffer, outBuffer) = (outBuffer, inBuffer)
610 let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
612 let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
614 guard let blurredImage = result else {
615 assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
625 /// Create an image from `self` with a color overlay layer.
627 /// - parameter color: The color should be use to overlay.
628 /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
630 /// - returns: An image with a color overlay applied.
632 /// - Note: This method only works for CG-based image.
633 public func overlaying(with color: Color, fraction: CGFloat) -> Image {
635 guard let cgImage = cgImage else {
636 assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
640 let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
641 return draw(cgImage: cgImage, to: rect.size) {
645 color.withAlphaComponent(1 - fraction).set()
646 rect.fill(using: .sourceAtop)
651 base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
654 base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
662 /// Create an image from `self` with a color tint.
664 /// - parameter color: The color should be used to tint `self`
666 /// - returns: An image with a color tint applied.
667 public func tinted(with color: Color) -> Image {
671 return apply(.tint(color))
675 // MARK: - Color Control
677 /// Create an image from `self` with color control.
679 /// - parameter brightness: Brightness changing to image.
680 /// - parameter contrast: Contrast changing to image.
681 /// - parameter saturation: Saturation changing to image.
682 /// - parameter inputEV: InputEV changing to image.
684 /// - returns: An image with color control applied.
685 public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
689 return apply(.colorControl((brightness, contrast, saturation, inputEV)))
693 /// Return an image with given scale.
695 /// - Parameter scale: Target scale factor the new image should have.
696 /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
697 public func scaled(to scale: CGFloat) -> Image {
698 guard scale != self.scale else {
701 guard let cgImage = cgImage else {
702 assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
705 return Kingfisher.image(cgImage: cgImage, scale: scale, refImage: base)
710 extension Kingfisher where Base: Image {
712 return decoded(scale: scale)
715 func decoded(scale: CGFloat) -> Image {
716 // prevent animated image (GIF) lose it's images
718 if imageSource != nil { return base }
720 if images != nil { return base }
723 guard let imageRef = self.cgImage else {
724 assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
728 // Draw CGImage in a plain context with scale of 1.0.
729 guard let context = beginContext(size: CGSize(width: imageRef.width, height: imageRef.height), scale: 1.0) else {
730 assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
734 defer { endContext() }
736 let rect = CGRect(x: 0, y: 0, width: CGFloat(imageRef.width), height: CGFloat(imageRef.height))
737 context.draw(imageRef, in: rect)
738 let decompressedImageRef = context.makeImage()
739 return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
743 /// Reference the source image reference
744 final class ImageSource {
745 var imageRef: CGImageSource?
746 init(ref: CGImageSource) {
751 // MARK: - Image format
752 private struct ImageHeaderData {
753 static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
754 static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
755 static var JPEG_IF: [UInt8] = [0xFF]
756 static var GIF: [UInt8] = [0x47, 0x49, 0x46]
760 case unknown, PNG, JPEG, GIF
764 // MARK: - Misc Helpers
765 public struct DataProxy {
766 fileprivate let base: Data
772 extension Data: KingfisherCompatible {
773 public typealias CompatibleType = DataProxy
774 public var kf: DataProxy {
775 return DataProxy(proxy: self)
779 extension DataProxy {
780 var imageFormat: ImageFormat {
781 var buffer = [UInt8](repeating: 0, count: 8)
782 (base as NSData).getBytes(&buffer, length: 8)
783 if buffer == ImageHeaderData.PNG {
785 } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
786 buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
787 buffer[2] == ImageHeaderData.JPEG_IF[0]
790 } else if buffer[0] == ImageHeaderData.GIF[0] &&
791 buffer[1] == ImageHeaderData.GIF[1] &&
792 buffer[2] == ImageHeaderData.GIF[2]
801 public struct CGSizeProxy {
802 fileprivate let base: CGSize
803 init(proxy: CGSize) {
808 extension CGSize: KingfisherCompatible {
809 public typealias CompatibleType = CGSizeProxy
810 public var kf: CGSizeProxy {
811 return CGSizeProxy(proxy: self)
815 extension CGSizeProxy {
816 func constrained(_ size: CGSize) -> CGSize {
817 let aspectWidth = round(aspectRatio * size.height)
818 let aspectHeight = round(size.width / aspectRatio)
820 return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
823 func filling(_ size: CGSize) -> CGSize {
824 let aspectWidth = round(aspectRatio * size.height)
825 let aspectHeight = round(size.width / aspectRatio)
827 return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
830 private var aspectRatio: CGFloat {
831 return base.height == 0.0 ? 1.0 : base.width / base.height
835 func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
837 let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
838 y: anchor.y.clamped(to: 0.0...1.0))
840 let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
841 let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
842 let r = CGRect(x: x, y: y, width: size.width, height: size.height)
844 let ori = CGRect(origin: CGPoint.zero, size: base)
845 return ori.intersection(r)
850 func scaled(_ scale: CGFloat) -> CGRect {
851 return CGRect(x: origin.x * scale, y: origin.y * scale,
852 width: size.width * scale, height: size.height * scale)
856 extension Comparable {
857 func clamped(to limits: ClosedRange<Self>) -> Self {
858 return min(max(self, limits.lowerBound), limits.upperBound)
862 extension Kingfisher where Base: Image {
864 func beginContext(size: CGSize, scale: CGFloat) -> CGContext? {
866 guard let rep = NSBitmapImageRep(
867 bitmapDataPlanes: nil,
868 pixelsWide: Int(size.width),
869 pixelsHigh: Int(size.height),
870 bitsPerSample: cgImage?.bitsPerComponent ?? 8,
874 colorSpaceName: .calibratedRGB,
876 bitsPerPixel: 0) else
878 assertionFailure("[Kingfisher] Image representation cannot be created.")
882 NSGraphicsContext.saveGraphicsState()
883 guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
884 assertionFailure("[Kingfisher] Image contenxt cannot be created.")
888 NSGraphicsContext.current = context
889 return context.cgContext
891 UIGraphicsBeginImageContextWithOptions(size, false, scale)
892 let context = UIGraphicsGetCurrentContext()
893 context?.scaleBy(x: 1.0, y: -1.0)
894 context?.translateBy(x: 0, y: -size.height)
901 NSGraphicsContext.restoreGraphicsState()
903 UIGraphicsEndImageContext()
907 func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
909 guard let rep = NSBitmapImageRep(
910 bitmapDataPlanes: nil,
911 pixelsWide: Int(size.width),
912 pixelsHigh: Int(size.height),
913 bitsPerSample: cgImage?.bitsPerComponent ?? 8,
917 colorSpaceName: .calibratedRGB,
919 bitsPerPixel: 0) else
921 assertionFailure("[Kingfisher] Image representation cannot be created.")
926 NSGraphicsContext.saveGraphicsState()
928 let context = NSGraphicsContext(bitmapImageRep: rep)
929 NSGraphicsContext.current = context
931 NSGraphicsContext.restoreGraphicsState()
933 let outputImage = Image(size: size)
934 outputImage.addRepresentation(rep)
938 UIGraphicsBeginImageContextWithOptions(size, false, scale)
939 defer { UIGraphicsEndImageContext() }
941 return UIGraphicsGetImageFromCurrentImageContext() ?? base
947 func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
949 let image = Image(cgImage: cgImage, size: base.size)
950 let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
952 return draw(cgImage: cgImage, to: self.size) {
953 image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
961 return truncatingRemainder(dividingBy: 2.0) == 0
966 extension NSBezierPath {
967 convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat,
968 bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat)
972 let maxCorner = min(rect.width, rect.height) / 2
974 let radiusTopLeft = min(maxCorner, max(0, topLeftRadius))
975 let radiustopRight = min(maxCorner, max(0, topRightRadius))
976 let radiusbottomLeft = min(maxCorner, max(0, bottomLeftRadius))
977 let radiusbottomRight = min(maxCorner, max(0, bottomRightRadius))
979 guard !NSIsEmptyRect(rect) else {
983 let topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect));
984 let topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect));
985 let bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect));
987 move(to: NSMakePoint(NSMidX(rect), NSMaxY(rect)))
988 appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft)
989 appendArc(from: rect.origin, to: bottomRight, radius: radiusbottomLeft)
990 appendArc(from: bottomRight, to: topRight, radius: radiusbottomRight)
991 appendArc(from: topRight, to: topLeft, radius: radiustopRight)
995 convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) {
996 let radiusTopLeft = corners.contains(.topLeft) ? radius : 0
997 let radiusTopRight = corners.contains(.topRight) ? radius : 0
998 let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0
999 let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0
1001 self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight,
1002 bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight)
1007 extension RectCorner {
1008 var uiRectCorner: UIRectCorner {
1010 var result: UIRectCorner = []
1012 if self.contains(.topLeft) { result.insert(.topLeft) }
1013 if self.contains(.topRight) { result.insert(.topRight) }
1014 if self.contains(.bottomLeft) { result.insert(.bottomLeft) }
1015 if self.contains(.bottomRight) { result.insert(.bottomRight) }