UIImage+Transform.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. /*
  2. * This file is part of the SDWebImage package.
  3. * (c) Olivier Poitrey <rs@dailymotion.com>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. #import "UIImage+Transform.h"
  9. #import "NSImage+Compatibility.h"
  10. #import "SDImageGraphics.h"
  11. #import "SDGraphicsImageRenderer.h"
  12. #import "NSBezierPath+SDRoundedCorners.h"
  13. #import <Accelerate/Accelerate.h>
  14. #if SD_UIKIT || SD_MAC
  15. #import <CoreImage/CoreImage.h>
  16. #endif
  17. static inline CGRect SDCGRectFitWithScaleMode(CGRect rect, CGSize size, SDImageScaleMode scaleMode) {
  18. rect = CGRectStandardize(rect);
  19. size.width = size.width < 0 ? -size.width : size.width;
  20. size.height = size.height < 0 ? -size.height : size.height;
  21. CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
  22. switch (scaleMode) {
  23. case SDImageScaleModeAspectFit:
  24. case SDImageScaleModeAspectFill: {
  25. if (rect.size.width < 0.01 || rect.size.height < 0.01 ||
  26. size.width < 0.01 || size.height < 0.01) {
  27. rect.origin = center;
  28. rect.size = CGSizeZero;
  29. } else {
  30. CGFloat scale;
  31. if (scaleMode == SDImageScaleModeAspectFit) {
  32. if (size.width / size.height < rect.size.width / rect.size.height) {
  33. scale = rect.size.height / size.height;
  34. } else {
  35. scale = rect.size.width / size.width;
  36. }
  37. } else {
  38. if (size.width / size.height < rect.size.width / rect.size.height) {
  39. scale = rect.size.width / size.width;
  40. } else {
  41. scale = rect.size.height / size.height;
  42. }
  43. }
  44. size.width *= scale;
  45. size.height *= scale;
  46. rect.size = size;
  47. rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5);
  48. }
  49. } break;
  50. case SDImageScaleModeFill:
  51. default: {
  52. rect = rect;
  53. }
  54. }
  55. return rect;
  56. }
  57. static inline UIColor * SDGetColorFromGrayscale(Pixel_88 pixel, CGBitmapInfo bitmapInfo, CGColorSpaceRef cgColorSpace) {
  58. // Get alpha info, byteOrder info
  59. CGImageAlphaInfo alphaInfo = bitmapInfo & kCGBitmapAlphaInfoMask;
  60. CGBitmapInfo byteOrderInfo = bitmapInfo & kCGBitmapByteOrderMask;
  61. CGFloat w = 0, a = 1;
  62. BOOL byteOrderNormal = NO;
  63. switch (byteOrderInfo) {
  64. case kCGBitmapByteOrderDefault: {
  65. byteOrderNormal = YES;
  66. } break;
  67. case kCGBitmapByteOrder32Little: {
  68. } break;
  69. case kCGBitmapByteOrder32Big: {
  70. byteOrderNormal = YES;
  71. } break;
  72. default: break;
  73. }
  74. switch (alphaInfo) {
  75. case kCGImageAlphaPremultipliedFirst:
  76. case kCGImageAlphaFirst: {
  77. if (byteOrderNormal) {
  78. // AW
  79. a = pixel[0] / 255.0;
  80. w = pixel[1] / 255.0;
  81. } else {
  82. // WA
  83. w = pixel[0] / 255.0;
  84. a = pixel[1] / 255.0;
  85. }
  86. }
  87. break;
  88. case kCGImageAlphaPremultipliedLast:
  89. case kCGImageAlphaLast: {
  90. if (byteOrderNormal) {
  91. // WA
  92. w = pixel[0] / 255.0;
  93. a = pixel[1] / 255.0;
  94. } else {
  95. // AW
  96. a = pixel[0] / 255.0;
  97. w = pixel[1] / 255.0;
  98. }
  99. }
  100. break;
  101. case kCGImageAlphaNone: {
  102. // W
  103. w = pixel[0] / 255.0;
  104. }
  105. break;
  106. case kCGImageAlphaNoneSkipLast: {
  107. if (byteOrderNormal) {
  108. // WX
  109. w = pixel[0] / 255.0;
  110. } else {
  111. // XW
  112. a = pixel[1] / 255.0;
  113. }
  114. }
  115. break;
  116. case kCGImageAlphaNoneSkipFirst: {
  117. if (byteOrderNormal) {
  118. // XW
  119. a = pixel[1] / 255.0;
  120. } else {
  121. // WX
  122. a = pixel[0] / 255.0;
  123. }
  124. }
  125. break;
  126. case kCGImageAlphaOnly: {
  127. // A
  128. a = pixel[0] / 255.0;
  129. }
  130. break;
  131. default:
  132. break;
  133. }
  134. #if SD_MAC
  135. // Mac supports ColorSync, to ensure the same bahvior, we convert color to sRGB
  136. NSColorSpace *colorSpace = [[NSColorSpace alloc] initWithCGColorSpace:cgColorSpace];
  137. CGFloat components[2] = {w, a};
  138. NSColor *color = [NSColor colorWithColorSpace:colorSpace components:components count:2];
  139. return [color colorUsingColorSpace:NSColorSpace.genericGamma22GrayColorSpace];
  140. #else
  141. return [UIColor colorWithWhite:w alpha:a];
  142. #endif
  143. }
  144. static inline UIColor * SDGetColorFromRGBA(Pixel_8888 pixel, CGBitmapInfo bitmapInfo, CGColorSpaceRef cgColorSpace) {
  145. // Get alpha info, byteOrder info
  146. CGImageAlphaInfo alphaInfo = bitmapInfo & kCGBitmapAlphaInfoMask;
  147. CGBitmapInfo byteOrderInfo = bitmapInfo & kCGBitmapByteOrderMask;
  148. CGFloat r = 0, g = 0, b = 0, a = 1;
  149. BOOL byteOrderNormal = NO;
  150. switch (byteOrderInfo) {
  151. case kCGBitmapByteOrderDefault: {
  152. byteOrderNormal = YES;
  153. } break;
  154. case kCGBitmapByteOrder16Little:
  155. case kCGBitmapByteOrder32Little: {
  156. } break;
  157. case kCGBitmapByteOrder16Big:
  158. case kCGBitmapByteOrder32Big: {
  159. byteOrderNormal = YES;
  160. } break;
  161. default: break;
  162. }
  163. switch (alphaInfo) {
  164. case kCGImageAlphaPremultipliedFirst:
  165. case kCGImageAlphaFirst: {
  166. if (byteOrderNormal) {
  167. // ARGB8888
  168. a = pixel[0] / 255.0;
  169. r = pixel[1] / 255.0;
  170. g = pixel[2] / 255.0;
  171. b = pixel[3] / 255.0;
  172. } else {
  173. // BGRA8888
  174. b = pixel[0] / 255.0;
  175. g = pixel[1] / 255.0;
  176. r = pixel[2] / 255.0;
  177. a = pixel[3] / 255.0;
  178. }
  179. }
  180. break;
  181. case kCGImageAlphaPremultipliedLast:
  182. case kCGImageAlphaLast: {
  183. if (byteOrderNormal) {
  184. // RGBA8888
  185. r = pixel[0] / 255.0;
  186. g = pixel[1] / 255.0;
  187. b = pixel[2] / 255.0;
  188. a = pixel[3] / 255.0;
  189. } else {
  190. // ABGR8888
  191. a = pixel[0] / 255.0;
  192. b = pixel[1] / 255.0;
  193. g = pixel[2] / 255.0;
  194. r = pixel[3] / 255.0;
  195. }
  196. }
  197. break;
  198. case kCGImageAlphaNone: {
  199. if (byteOrderNormal) {
  200. // RGB
  201. r = pixel[0] / 255.0;
  202. g = pixel[1] / 255.0;
  203. b = pixel[2] / 255.0;
  204. } else {
  205. // BGR
  206. b = pixel[0] / 255.0;
  207. g = pixel[1] / 255.0;
  208. r = pixel[2] / 255.0;
  209. }
  210. }
  211. break;
  212. case kCGImageAlphaNoneSkipLast: {
  213. if (byteOrderNormal) {
  214. // RGBX
  215. r = pixel[0] / 255.0;
  216. g = pixel[1] / 255.0;
  217. b = pixel[2] / 255.0;
  218. } else {
  219. // XBGR
  220. b = pixel[1] / 255.0;
  221. g = pixel[2] / 255.0;
  222. r = pixel[3] / 255.0;
  223. }
  224. }
  225. break;
  226. case kCGImageAlphaNoneSkipFirst: {
  227. if (byteOrderNormal) {
  228. // XRGB
  229. r = pixel[1] / 255.0;
  230. g = pixel[2] / 255.0;
  231. b = pixel[3] / 255.0;
  232. } else {
  233. // BGRX
  234. b = pixel[0] / 255.0;
  235. g = pixel[1] / 255.0;
  236. r = pixel[2] / 255.0;
  237. }
  238. }
  239. break;
  240. case kCGImageAlphaOnly: {
  241. // A
  242. a = pixel[0] / 255.0;
  243. }
  244. break;
  245. default:
  246. break;
  247. }
  248. #if SD_MAC
  249. // Mac supports ColorSync, to ensure the same bahvior, we convert color to sRGB
  250. NSColorSpace *colorSpace = [[NSColorSpace alloc] initWithCGColorSpace:cgColorSpace];
  251. CGFloat components[4] = {r, g, b, a};
  252. NSColor *color = [NSColor colorWithColorSpace:colorSpace components:components count:4];
  253. return [color colorUsingColorSpace:NSColorSpace.sRGBColorSpace];
  254. #else
  255. return [UIColor colorWithRed:r green:g blue:b alpha:a];
  256. #endif
  257. }
  258. #if SD_UIKIT || SD_MAC
  259. // Create-Rule, caller should call CGImageRelease
  260. static inline CGImageRef _Nullable SDCreateCGImageFromCIImage(CIImage * _Nonnull ciImage) {
  261. CGImageRef imageRef = NULL;
  262. if (@available(iOS 10, macOS 10.12, tvOS 10, *)) {
  263. imageRef = ciImage.CGImage;
  264. }
  265. if (!imageRef) {
  266. CIContext *context = [CIContext context];
  267. imageRef = [context createCGImage:ciImage fromRect:ciImage.extent];
  268. } else {
  269. CGImageRetain(imageRef);
  270. }
  271. return imageRef;
  272. }
  273. #endif
  274. @implementation UIImage (Transform)
  275. - (void)sd_drawInRect:(CGRect)rect context:(CGContextRef)context scaleMode:(SDImageScaleMode)scaleMode clipsToBounds:(BOOL)clips {
  276. CGRect drawRect = SDCGRectFitWithScaleMode(rect, self.size, scaleMode);
  277. if (drawRect.size.width == 0 || drawRect.size.height == 0) return;
  278. if (clips) {
  279. if (context) {
  280. CGContextSaveGState(context);
  281. CGContextAddRect(context, rect);
  282. CGContextClip(context);
  283. [self drawInRect:drawRect];
  284. CGContextRestoreGState(context);
  285. }
  286. } else {
  287. [self drawInRect:drawRect];
  288. }
  289. }
  290. - (nullable UIImage *)sd_resizedImageWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode {
  291. if (size.width <= 0 || size.height <= 0) return nil;
  292. SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init];
  293. format.scale = self.scale;
  294. SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:size format:format];
  295. UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) {
  296. [self sd_drawInRect:CGRectMake(0, 0, size.width, size.height) context:context scaleMode:scaleMode clipsToBounds:NO];
  297. }];
  298. return image;
  299. }
  300. - (nullable UIImage *)sd_croppedImageWithRect:(CGRect)rect {
  301. rect.origin.x *= self.scale;
  302. rect.origin.y *= self.scale;
  303. rect.size.width *= self.scale;
  304. rect.size.height *= self.scale;
  305. if (rect.size.width <= 0 || rect.size.height <= 0) return nil;
  306. #if SD_UIKIT || SD_MAC
  307. // CIImage shortcut
  308. if (self.CIImage) {
  309. CGRect croppingRect = CGRectMake(rect.origin.x, self.size.height - CGRectGetMaxY(rect), rect.size.width, rect.size.height);
  310. CIImage *ciImage = [self.CIImage imageByCroppingToRect:croppingRect];
  311. #if SD_UIKIT
  312. UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation];
  313. #else
  314. UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp];
  315. #endif
  316. return image;
  317. }
  318. #endif
  319. CGImageRef imageRef = self.CGImage;
  320. if (!imageRef) {
  321. return nil;
  322. }
  323. CGImageRef croppedImageRef = CGImageCreateWithImageInRect(imageRef, rect);
  324. if (!croppedImageRef) {
  325. return nil;
  326. }
  327. #if SD_UIKIT || SD_WATCH
  328. UIImage *image = [UIImage imageWithCGImage:croppedImageRef scale:self.scale orientation:self.imageOrientation];
  329. #else
  330. UIImage *image = [[UIImage alloc] initWithCGImage:croppedImageRef scale:self.scale orientation:kCGImagePropertyOrientationUp];
  331. #endif
  332. CGImageRelease(croppedImageRef);
  333. return image;
  334. }
  335. - (nullable UIImage *)sd_roundedCornerImageWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(nullable UIColor *)borderColor {
  336. SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init];
  337. format.scale = self.scale;
  338. SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:self.size format:format];
  339. UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) {
  340. CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
  341. CGFloat minSize = MIN(self.size.width, self.size.height);
  342. if (borderWidth < minSize / 2) {
  343. #if SD_UIKIT || SD_WATCH
  344. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
  345. #else
  346. NSBezierPath *path = [NSBezierPath sd_bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadius:cornerRadius];
  347. #endif
  348. [path closePath];
  349. CGContextSaveGState(context);
  350. [path addClip];
  351. [self drawInRect:rect];
  352. CGContextRestoreGState(context);
  353. }
  354. if (borderColor && borderWidth < minSize / 2 && borderWidth > 0) {
  355. CGFloat strokeInset = (floor(borderWidth * self.scale) + 0.5) / self.scale;
  356. CGRect strokeRect = CGRectInset(rect, strokeInset, strokeInset);
  357. CGFloat strokeRadius = cornerRadius > self.scale / 2 ? cornerRadius - self.scale / 2 : 0;
  358. #if SD_UIKIT || SD_WATCH
  359. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadii:CGSizeMake(strokeRadius, strokeRadius)];
  360. #else
  361. NSBezierPath *path = [NSBezierPath sd_bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadius:strokeRadius];
  362. #endif
  363. [path closePath];
  364. path.lineWidth = borderWidth;
  365. [borderColor setStroke];
  366. [path stroke];
  367. }
  368. }];
  369. return image;
  370. }
  371. - (nullable UIImage *)sd_rotatedImageWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize {
  372. size_t width = self.size.width;
  373. size_t height = self.size.height;
  374. CGRect newRect = CGRectApplyAffineTransform(CGRectMake(0, 0, width, height),
  375. fitSize ? CGAffineTransformMakeRotation(angle) : CGAffineTransformIdentity);
  376. #if SD_UIKIT || SD_MAC
  377. // CIImage shortcut
  378. if (self.CIImage) {
  379. CIImage *ciImage = self.CIImage;
  380. if (fitSize) {
  381. CGAffineTransform transform = CGAffineTransformMakeRotation(angle);
  382. ciImage = [ciImage imageByApplyingTransform:transform];
  383. } else {
  384. CIFilter *filter = [CIFilter filterWithName:@"CIStraightenFilter"];
  385. [filter setValue:ciImage forKey:kCIInputImageKey];
  386. [filter setValue:@(angle) forKey:kCIInputAngleKey];
  387. ciImage = filter.outputImage;
  388. }
  389. #if SD_UIKIT || SD_WATCH
  390. UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation];
  391. #else
  392. UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp];
  393. #endif
  394. return image;
  395. }
  396. #endif
  397. SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init];
  398. format.scale = self.scale;
  399. SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:newRect.size format:format];
  400. UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) {
  401. CGContextSetShouldAntialias(context, true);
  402. CGContextSetAllowsAntialiasing(context, true);
  403. CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
  404. CGContextTranslateCTM(context, +(newRect.size.width * 0.5), +(newRect.size.height * 0.5));
  405. #if SD_UIKIT || SD_WATCH
  406. // Use UIKit coordinate system counterclockwise (⟲)
  407. CGContextRotateCTM(context, -angle);
  408. #else
  409. CGContextRotateCTM(context, angle);
  410. #endif
  411. [self drawInRect:CGRectMake(-(width * 0.5), -(height * 0.5), width, height)];
  412. }];
  413. return image;
  414. }
  415. - (nullable UIImage *)sd_flippedImageWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical {
  416. size_t width = self.size.width;
  417. size_t height = self.size.height;
  418. #if SD_UIKIT || SD_MAC
  419. // CIImage shortcut
  420. if (self.CIImage) {
  421. CGAffineTransform transform = CGAffineTransformIdentity;
  422. // Use UIKit coordinate system
  423. if (horizontal) {
  424. CGAffineTransform flipHorizontal = CGAffineTransformMake(-1, 0, 0, 1, width, 0);
  425. transform = CGAffineTransformConcat(transform, flipHorizontal);
  426. }
  427. if (vertical) {
  428. CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, height);
  429. transform = CGAffineTransformConcat(transform, flipVertical);
  430. }
  431. CIImage *ciImage = [self.CIImage imageByApplyingTransform:transform];
  432. #if SD_UIKIT
  433. UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation];
  434. #else
  435. UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp];
  436. #endif
  437. return image;
  438. }
  439. #endif
  440. SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init];
  441. format.scale = self.scale;
  442. SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:self.size format:format];
  443. UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) {
  444. // Use UIKit coordinate system
  445. if (horizontal) {
  446. CGAffineTransform flipHorizontal = CGAffineTransformMake(-1, 0, 0, 1, width, 0);
  447. CGContextConcatCTM(context, flipHorizontal);
  448. }
  449. if (vertical) {
  450. CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, height);
  451. CGContextConcatCTM(context, flipVertical);
  452. }
  453. [self drawInRect:CGRectMake(0, 0, width, height)];
  454. }];
  455. return image;
  456. }
  457. #pragma mark - Image Blending
  458. - (nullable UIImage *)sd_tintedImageWithColor:(nonnull UIColor *)tintColor {
  459. BOOL hasTint = CGColorGetAlpha(tintColor.CGColor) > __FLT_EPSILON__;
  460. if (!hasTint) {
  461. return self;
  462. }
  463. #if SD_UIKIT || SD_MAC
  464. // CIImage shortcut
  465. if (self.CIImage) {
  466. CIImage *ciImage = self.CIImage;
  467. CIImage *colorImage = [CIImage imageWithColor:[[CIColor alloc] initWithColor:tintColor]];
  468. colorImage = [colorImage imageByCroppingToRect:ciImage.extent];
  469. CIFilter *filter = [CIFilter filterWithName:@"CISourceAtopCompositing"];
  470. [filter setValue:colorImage forKey:kCIInputImageKey];
  471. [filter setValue:ciImage forKey:kCIInputBackgroundImageKey];
  472. ciImage = filter.outputImage;
  473. #if SD_UIKIT
  474. UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation];
  475. #else
  476. UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp];
  477. #endif
  478. return image;
  479. }
  480. #endif
  481. CGSize size = self.size;
  482. CGRect rect = { CGPointZero, size };
  483. CGFloat scale = self.scale;
  484. // blend mode, see https://en.wikipedia.org/wiki/Alpha_compositing
  485. CGBlendMode blendMode = kCGBlendModeSourceAtop;
  486. SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init];
  487. format.scale = scale;
  488. SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:size format:format];
  489. UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) {
  490. [self drawInRect:rect];
  491. CGContextSetBlendMode(context, blendMode);
  492. CGContextSetFillColorWithColor(context, tintColor.CGColor);
  493. CGContextFillRect(context, rect);
  494. }];
  495. return image;
  496. }
  497. - (nullable UIColor *)sd_colorAtPoint:(CGPoint)point {
  498. CGImageRef imageRef = NULL;
  499. // CIImage compatible
  500. #if SD_UIKIT || SD_MAC
  501. if (self.CIImage) {
  502. imageRef = SDCreateCGImageFromCIImage(self.CIImage);
  503. }
  504. #endif
  505. if (!imageRef) {
  506. imageRef = self.CGImage;
  507. CGImageRetain(imageRef);
  508. }
  509. if (!imageRef) {
  510. return nil;
  511. }
  512. // Check point
  513. CGFloat width = CGImageGetWidth(imageRef);
  514. CGFloat height = CGImageGetHeight(imageRef);
  515. if (point.x < 0 || point.y < 0 || point.x >= width || point.y >= height) {
  516. CGImageRelease(imageRef);
  517. return nil;
  518. }
  519. // Get pixels
  520. CGDataProviderRef provider = CGImageGetDataProvider(imageRef);
  521. if (!provider) {
  522. CGImageRelease(imageRef);
  523. return nil;
  524. }
  525. CFDataRef data = CGDataProviderCopyData(provider);
  526. if (!data) {
  527. CGImageRelease(imageRef);
  528. return nil;
  529. }
  530. // Get pixel at point
  531. size_t bytesPerRow = CGImageGetBytesPerRow(imageRef);
  532. size_t components = CGImageGetBitsPerPixel(imageRef) / CGImageGetBitsPerComponent(imageRef);
  533. CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
  534. CFRange range = CFRangeMake(bytesPerRow * point.y + components * point.x, components);
  535. if (CFDataGetLength(data) < range.location + range.length) {
  536. CFRelease(data);
  537. CGImageRelease(imageRef);
  538. return nil;
  539. }
  540. // Get color space for transform
  541. CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);
  542. // greyscale
  543. if (components == 2) {
  544. Pixel_88 pixel = {0};
  545. CFDataGetBytes(data, range, pixel);
  546. CFRelease(data);
  547. CGImageRelease(imageRef);
  548. // Convert to color
  549. return SDGetColorFromGrayscale(pixel, bitmapInfo, colorSpace);
  550. } else if (components == 3 || components == 4) {
  551. // RGB/RGBA
  552. Pixel_8888 pixel = {0};
  553. CFDataGetBytes(data, range, pixel);
  554. CFRelease(data);
  555. CGImageRelease(imageRef);
  556. // Convert to color
  557. return SDGetColorFromRGBA(pixel, bitmapInfo, colorSpace);
  558. } else {
  559. NSLog(@"Unsupported components: %zu", components);
  560. CFRelease(data);
  561. CGImageRelease(imageRef);
  562. return nil;
  563. }
  564. }
  565. - (nullable NSArray<UIColor *> *)sd_colorsWithRect:(CGRect)rect {
  566. CGImageRef imageRef = NULL;
  567. // CIImage compatible
  568. #if SD_UIKIT || SD_MAC
  569. if (self.CIImage) {
  570. imageRef = SDCreateCGImageFromCIImage(self.CIImage);
  571. }
  572. #endif
  573. if (!imageRef) {
  574. imageRef = self.CGImage;
  575. CGImageRetain(imageRef);
  576. }
  577. if (!imageRef) {
  578. return nil;
  579. }
  580. // Check rect
  581. CGFloat width = CGImageGetWidth(imageRef);
  582. CGFloat height = CGImageGetHeight(imageRef);
  583. if (CGRectGetWidth(rect) <= 0 || CGRectGetHeight(rect) <= 0 || CGRectGetMinX(rect) < 0 || CGRectGetMinY(rect) < 0 || CGRectGetMaxX(rect) > width || CGRectGetMaxY(rect) > height) {
  584. CGImageRelease(imageRef);
  585. return nil;
  586. }
  587. // Get pixels
  588. CGDataProviderRef provider = CGImageGetDataProvider(imageRef);
  589. if (!provider) {
  590. CGImageRelease(imageRef);
  591. return nil;
  592. }
  593. CFDataRef data = CGDataProviderCopyData(provider);
  594. if (!data) {
  595. CGImageRelease(imageRef);
  596. return nil;
  597. }
  598. // Get pixels with rect
  599. size_t bytesPerRow = CGImageGetBytesPerRow(imageRef);
  600. size_t components = CGImageGetBitsPerPixel(imageRef) / CGImageGetBitsPerComponent(imageRef);
  601. size_t start = bytesPerRow * CGRectGetMinY(rect) + components * CGRectGetMinX(rect);
  602. size_t end = bytesPerRow * (CGRectGetMaxY(rect) - 1) + components * CGRectGetMaxX(rect);
  603. if (CFDataGetLength(data) < (CFIndex)end) {
  604. CFRelease(data);
  605. CGImageRelease(imageRef);
  606. return nil;
  607. }
  608. const UInt8 *pixels = CFDataGetBytePtr(data);
  609. size_t row = CGRectGetMinY(rect);
  610. size_t col = CGRectGetMaxX(rect);
  611. // Convert to color
  612. CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
  613. NSMutableArray<UIColor *> *colors = [NSMutableArray arrayWithCapacity:CGRectGetWidth(rect) * CGRectGetHeight(rect)];
  614. // ColorSpace
  615. CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);
  616. for (size_t index = start; index < end; index += components) {
  617. if (index >= row * bytesPerRow + col * components) {
  618. // Index beyond the end of current row, go next row
  619. row++;
  620. index = row * bytesPerRow + CGRectGetMinX(rect) * components;
  621. index -= components;
  622. continue;
  623. }
  624. UIColor *color;
  625. if (components == 2) {
  626. Pixel_88 pixel = {pixels[index], pixel[index+1]};
  627. color = SDGetColorFromGrayscale(pixel, bitmapInfo, colorSpace);
  628. } else {
  629. if (components == 3) {
  630. Pixel_8888 pixel = {pixels[index], pixels[index+1], pixels[index+2], 0};
  631. color = SDGetColorFromRGBA(pixel, bitmapInfo, colorSpace);
  632. } else if (components == 4) {
  633. Pixel_8888 pixel = {pixels[index], pixels[index+1], pixels[index+2], pixels[index+3]};
  634. color = SDGetColorFromRGBA(pixel, bitmapInfo, colorSpace);
  635. } else {
  636. NSLog(@"Unsupported components: %zu", components);
  637. }
  638. }
  639. if (color) {
  640. [colors addObject:color];
  641. }
  642. }
  643. CFRelease(data);
  644. CGImageRelease(imageRef);
  645. return [colors copy];
  646. }
  647. #pragma mark - Image Effect
  648. // We use vImage to do box convolve for performance and support for watchOS. However, you can just use `CIFilter.CIGaussianBlur`. For other blur effect, use any filter in `CICategoryBlur`
  649. - (nullable UIImage *)sd_blurredImageWithRadius:(CGFloat)blurRadius {
  650. if (self.size.width < 1 || self.size.height < 1) {
  651. return nil;
  652. }
  653. BOOL hasBlur = blurRadius > __FLT_EPSILON__;
  654. if (!hasBlur) {
  655. return self;
  656. }
  657. CGFloat scale = self.scale;
  658. CGFloat inputRadius = blurRadius * scale;
  659. #if SD_UIKIT || SD_MAC
  660. if (self.CIImage) {
  661. CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
  662. [filter setValue:self.CIImage forKey:kCIInputImageKey];
  663. [filter setValue:@(inputRadius) forKey:kCIInputRadiusKey];
  664. CIImage *ciImage = filter.outputImage;
  665. ciImage = [ciImage imageByCroppingToRect:CGRectMake(0, 0, self.size.width, self.size.height)];
  666. #if SD_UIKIT
  667. UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation];
  668. #else
  669. UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp];
  670. #endif
  671. return image;
  672. }
  673. #endif
  674. CGImageRef imageRef = self.CGImage;
  675. if (!imageRef) {
  676. return nil;
  677. }
  678. vImage_Buffer effect = {}, scratch = {};
  679. vImage_Buffer *input = NULL, *output = NULL;
  680. vImage_CGImageFormat format = {
  681. .bitsPerComponent = 8,
  682. .bitsPerPixel = 32,
  683. .colorSpace = NULL,
  684. .bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, //requests a BGRA buffer.
  685. .version = 0,
  686. .decode = NULL,
  687. .renderingIntent = CGImageGetRenderingIntent(imageRef)
  688. };
  689. vImage_Error err;
  690. err = vImageBuffer_InitWithCGImage(&effect, &format, NULL, imageRef, kvImageNoFlags); // vImage will convert to format we requests, no need `vImageConvert`
  691. if (err != kvImageNoError) {
  692. NSLog(@"UIImage+Transform error: vImageBuffer_InitWithCGImage returned error code %zi for inputImage: %@", err, self);
  693. return nil;
  694. }
  695. err = vImageBuffer_Init(&scratch, effect.height, effect.width, format.bitsPerPixel, kvImageNoFlags);
  696. if (err != kvImageNoError) {
  697. NSLog(@"UIImage+Transform error: vImageBuffer_Init returned error code %zi for inputImage: %@", err, self);
  698. return nil;
  699. }
  700. input = &effect;
  701. output = &scratch;
  702. // See: https://developer.apple.com/library/archive/samplecode/UIImageEffects/Introduction/Intro.html
  703. if (hasBlur) {
  704. // A description of how to compute the box kernel width from the Gaussian
  705. // radius (aka standard deviation) appears in the SVG spec:
  706. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  707. //
  708. // For larger values of 's' (s >= 2.0), an approximation can be used: Three
  709. // successive box-blurs build a piece-wise quadratic convolution kernel, which
  710. // approximates the Gaussian kernel to within roughly 3%.
  711. //
  712. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  713. //
  714. // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  715. //
  716. if (inputRadius - 2.0 < __FLT_EPSILON__) inputRadius = 2.0;
  717. uint32_t radius = floor(inputRadius * 3.0 * sqrt(2 * M_PI) / 4 + 0.5);
  718. radius |= 1; // force radius to be odd so that the three box-blur methodology works.
  719. NSInteger tempSize = vImageBoxConvolve_ARGB8888(input, output, NULL, 0, 0, radius, radius, NULL, kvImageGetTempBufferSize | kvImageEdgeExtend);
  720. void *temp = malloc(tempSize);
  721. vImageBoxConvolve_ARGB8888(input, output, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend);
  722. vImageBoxConvolve_ARGB8888(output, input, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend);
  723. vImageBoxConvolve_ARGB8888(input, output, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend);
  724. free(temp);
  725. vImage_Buffer *tmp = input;
  726. input = output;
  727. output = tmp;
  728. }
  729. CGImageRef effectCGImage = NULL;
  730. effectCGImage = vImageCreateCGImageFromBuffer(input, &format, NULL, NULL, kvImageNoAllocate, NULL);
  731. if (effectCGImage == NULL) {
  732. effectCGImage = vImageCreateCGImageFromBuffer(input, &format, NULL, NULL, kvImageNoFlags, NULL);
  733. free(input->data);
  734. }
  735. free(output->data);
  736. #if SD_UIKIT || SD_WATCH
  737. UIImage *outputImage = [UIImage imageWithCGImage:effectCGImage scale:self.scale orientation:self.imageOrientation];
  738. #else
  739. UIImage *outputImage = [[UIImage alloc] initWithCGImage:effectCGImage scale:self.scale orientation:kCGImagePropertyOrientationUp];
  740. #endif
  741. CGImageRelease(effectCGImage);
  742. return outputImage;
  743. }
  744. #if SD_UIKIT || SD_MAC
  745. - (nullable UIImage *)sd_filteredImageWithFilter:(nonnull CIFilter *)filter {
  746. CIImage *inputImage;
  747. if (self.CIImage) {
  748. inputImage = self.CIImage;
  749. } else {
  750. CGImageRef imageRef = self.CGImage;
  751. if (!imageRef) {
  752. return nil;
  753. }
  754. inputImage = [CIImage imageWithCGImage:imageRef];
  755. }
  756. if (!inputImage) return nil;
  757. CIContext *context = [CIContext context];
  758. [filter setValue:inputImage forKey:kCIInputImageKey];
  759. CIImage *outputImage = filter.outputImage;
  760. if (!outputImage) return nil;
  761. CGImageRef imageRef = [context createCGImage:outputImage fromRect:outputImage.extent];
  762. if (!imageRef) return nil;
  763. #if SD_UIKIT
  764. UIImage *image = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
  765. #else
  766. UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:self.scale orientation:kCGImagePropertyOrientationUp];
  767. #endif
  768. CGImageRelease(imageRef);
  769. return image;
  770. }
  771. #endif
  772. @end