UIImage+AHKAdditions.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*
  2. File: UIImage+ImageEffects.m
  3. Abstract: This is a category of UIImage that adds methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur.
  4. Version: 1.0
  5. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
  6. Inc. ("Apple") in consideration of your agreement to the following
  7. terms, and your use, installation, modification or redistribution of
  8. this Apple software constitutes acceptance of these terms. If you do
  9. not agree with these terms, please do not use, install, modify or
  10. redistribute this Apple software.
  11. In consideration of your agreement to abide by the following terms, and
  12. subject to these terms, Apple grants you a personal, non-exclusive
  13. license, under Apple's copyrights in this original Apple software (the
  14. "Apple Software"), to use, reproduce, modify and redistribute the Apple
  15. Software, with or without modifications, in source and/or binary forms;
  16. provided that if you redistribute the Apple Software in its entirety and
  17. without modifications, you must retain this notice and the following
  18. text and disclaimers in all such redistributions of the Apple Software.
  19. Neither the name, trademarks, service marks or logos of Apple Inc. may
  20. be used to endorse or promote products derived from the Apple Software
  21. without specific prior written permission from Apple. Except as
  22. expressly stated in this notice, no other rights or licenses, express or
  23. implied, are granted by Apple herein, including but not limited to any
  24. patent rights that may be infringed by your derivative works or by other
  25. works in which the Apple Software may be incorporated.
  26. The Apple Software is provided by Apple on an "AS IS" basis. APPLE
  27. MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  28. THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
  29. FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
  30. OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
  31. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
  32. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  33. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  34. INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
  35. MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
  36. AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
  37. STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
  38. POSSIBILITY OF SUCH DAMAGE.
  39. Copyright (C) 2013 Apple Inc. All Rights Reserved.
  40. Copyright © 2013 Apple Inc. All rights reserved.
  41. WWDC 2013 License
  42. NOTE: This Apple Software was supplied by Apple as part of a WWDC 2013
  43. Session. Please refer to the applicable WWDC 2013 Session for further
  44. information.
  45. IMPORTANT: This Apple software is supplied to you by Apple Inc.
  46. ("Apple") in consideration of your agreement to the following terms, and
  47. your use, installation, modification or redistribution of this Apple
  48. software constitutes acceptance of these terms. If you do not agree with
  49. these terms, please do not use, install, modify or redistribute this
  50. Apple software.
  51. In consideration of your agreement to abide by the following terms, and
  52. subject to these terms, Apple grants you a non-exclusive license, under
  53. Apple's copyrights in this original Apple software (the "Apple
  54. Software"), to use, reproduce, modify and redistribute the Apple
  55. Software, with or without modifications, in source and/or binary forms;
  56. provided that if you redistribute the Apple Software in its entirety and
  57. without modifications, you must retain this notice and the following
  58. text and disclaimers in all such redistributions of the Apple Software.
  59. Neither the name, trademarks, service marks or logos of Apple Inc. may
  60. be used to endorse or promote products derived from the Apple Software
  61. without specific prior written permission from Apple. Except as
  62. expressly stated in this notice, no other rights or licenses, express or
  63. implied, are granted by Apple herein, including but not limited to any
  64. patent rights that may be infringed by your derivative works or by other
  65. works in which the Apple Software may be incorporated.
  66. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES
  67. NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
  68. IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR
  69. A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
  70. OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
  71. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
  72. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  73. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  74. INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
  75. MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
  76. AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
  77. STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
  78. POSSIBILITY OF SUCH DAMAGE.
  79. EA1002
  80. 5/3/2013
  81. */
  82. #import "UIImage+AHKAdditions.h"
  83. @import Accelerate;
  84. #import <float.h>
  85. @implementation UIImage (AHKAdditions)
  86. - (UIImage *)ahk_applyLightEffect
  87. {
  88. UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3f];
  89. return [self ahk_applyBlurWithRadius:30 tintColor:tintColor saturationDeltaFactor:1.8f maskImage:nil];
  90. }
  91. - (UIImage *)ahk_applyExtraLightEffect
  92. {
  93. UIColor *tintColor = [UIColor colorWithWhite:0.97f alpha:0.82f];
  94. return [self ahk_applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8f maskImage:nil];
  95. }
  96. - (UIImage *)ahk_applyDarkEffect
  97. {
  98. UIColor *tintColor = [UIColor colorWithWhite:0.11f alpha:0.73f];
  99. return [self ahk_applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8f maskImage:nil];
  100. }
  101. - (UIImage *)ahk_applyTintEffectWithColor:(UIColor *)tintColor
  102. {
  103. const CGFloat EffectColorAlpha = 0.6f;
  104. UIColor *effectColor = tintColor;
  105. int componentCount = (int)CGColorGetNumberOfComponents(tintColor.CGColor);
  106. if (componentCount == 2) {
  107. CGFloat b;
  108. if ([tintColor getWhite:&b alpha:NULL]) {
  109. effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
  110. }
  111. }
  112. else {
  113. CGFloat r, g, b;
  114. if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
  115. effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
  116. }
  117. }
  118. return [self ahk_applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
  119. }
  120. - (UIImage *)ahk_applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
  121. {
  122. // Check pre-conditions.
  123. if (self.size.width < 1 || self.size.height < 1) {
  124. NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
  125. return nil;
  126. }
  127. if (!self.CGImage) {
  128. NSLog (@"*** error: image must be backed by a CGImage: %@", self);
  129. return nil;
  130. }
  131. if (maskImage && !maskImage.CGImage) {
  132. NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
  133. return nil;
  134. }
  135. CGRect imageRect = { CGPointZero, self.size };
  136. UIImage *effectImage = self;
  137. BOOL hasBlur = blurRadius > __FLT_EPSILON__;
  138. BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
  139. if (hasBlur || hasSaturationChange) {
  140. UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
  141. CGContextRef effectInContext = UIGraphicsGetCurrentContext();
  142. CGContextScaleCTM(effectInContext, 1.0, -1.0);
  143. CGContextTranslateCTM(effectInContext, 0, -self.size.height);
  144. CGContextDrawImage(effectInContext, imageRect, self.CGImage);
  145. vImage_Buffer effectInBuffer;
  146. effectInBuffer.data = CGBitmapContextGetData(effectInContext);
  147. effectInBuffer.width = CGBitmapContextGetWidth(effectInContext);
  148. effectInBuffer.height = CGBitmapContextGetHeight(effectInContext);
  149. effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);
  150. UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
  151. CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
  152. vImage_Buffer effectOutBuffer;
  153. effectOutBuffer.data = CGBitmapContextGetData(effectOutContext);
  154. effectOutBuffer.width = CGBitmapContextGetWidth(effectOutContext);
  155. effectOutBuffer.height = CGBitmapContextGetHeight(effectOutContext);
  156. effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);
  157. if (hasBlur) {
  158. // A description of how to compute the box kernel width from the Gaussian
  159. // radius (aka standard deviation) appears in the SVG spec:
  160. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  161. //
  162. // For larger values of 's' (s >= 2.0), an approximation can be used: Three
  163. // successive box-blurs build a piece-wise quadratic convolution kernel, which
  164. // approximates the Gaussian kernel to within roughly 3%.
  165. //
  166. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  167. //
  168. // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  169. //
  170. CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
  171. uint32_t radius = (uint32_t)floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
  172. if (radius % 2 != 1) {
  173. radius += 1; // force radius to be odd so that the three box-blur methodology works.
  174. }
  175. vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
  176. vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
  177. vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
  178. }
  179. BOOL effectImageBuffersAreSwapped = NO;
  180. if (hasSaturationChange) {
  181. CGFloat s = saturationDeltaFactor;
  182. CGFloat floatingPointSaturationMatrix[] = {
  183. 0.0722f + 0.9278f * s, 0.0722f - 0.0722f * s, 0.0722f - 0.0722f * s, 0,
  184. 0.7152f - 0.7152f * s, 0.7152f + 0.2848f * s, 0.7152f - 0.7152f * s, 0,
  185. 0.2126f - 0.2126f * s, 0.2126f - 0.2126f * s, 0.2126f + 0.7873f * s, 0,
  186. 0, 0, 0, 1,
  187. };
  188. const int32_t divisor = 256;
  189. NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
  190. int16_t saturationMatrix[matrixSize];
  191. for (NSUInteger i = 0; i < matrixSize; ++i) {
  192. saturationMatrix[i] = (int16_t)round(floatingPointSaturationMatrix[i] * divisor);
  193. }
  194. if (hasBlur) {
  195. vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
  196. effectImageBuffersAreSwapped = YES;
  197. }
  198. else {
  199. vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
  200. }
  201. }
  202. if (!effectImageBuffersAreSwapped)
  203. effectImage = UIGraphicsGetImageFromCurrentImageContext();
  204. UIGraphicsEndImageContext();
  205. if (effectImageBuffersAreSwapped)
  206. effectImage = UIGraphicsGetImageFromCurrentImageContext();
  207. UIGraphicsEndImageContext();
  208. }
  209. // Set up output context.
  210. UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
  211. CGContextRef outputContext = UIGraphicsGetCurrentContext();
  212. CGContextScaleCTM(outputContext, 1.0, -1.0);
  213. CGContextTranslateCTM(outputContext, 0, -self.size.height);
  214. // Draw base image.
  215. CGContextDrawImage(outputContext, imageRect, self.CGImage);
  216. // Draw effect image.
  217. if (hasBlur) {
  218. CGContextSaveGState(outputContext);
  219. if (maskImage) {
  220. CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
  221. }
  222. CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
  223. CGContextRestoreGState(outputContext);
  224. }
  225. // Add in color tint.
  226. if (tintColor) {
  227. CGContextSaveGState(outputContext);
  228. CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
  229. CGContextFillRect(outputContext, imageRect);
  230. CGContextRestoreGState(outputContext);
  231. }
  232. // Output image is ready.
  233. UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
  234. UIGraphicsEndImageContext();
  235. return outputImage;
  236. }
  237. @end