YYTextAsyncLayer.m 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. //
  2. // YYTextAsyncLayer.m
  3. // YYText <https://github.com/ibireme/YYText>
  4. //
  5. // Created by ibireme on 15/4/11.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import "YYTextAsyncLayer.h"
  12. #import <libkern/OSAtomic.h>
  13. /// Global display queue, used for content rendering.
  14. static dispatch_queue_t YYTextAsyncLayerGetDisplayQueue() {
  15. #define MAX_QUEUE_COUNT 16
  16. static int queueCount;
  17. static dispatch_queue_t queues[MAX_QUEUE_COUNT];
  18. static dispatch_once_t onceToken;
  19. static int32_t counter = 0;
  20. dispatch_once(&onceToken, ^{
  21. queueCount = (int)[NSProcessInfo processInfo].activeProcessorCount;
  22. queueCount = queueCount < 1 ? 1 : queueCount > MAX_QUEUE_COUNT ? MAX_QUEUE_COUNT : queueCount;
  23. if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
  24. for (NSUInteger i = 0; i < queueCount; i++) {
  25. dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0);
  26. queues[i] = dispatch_queue_create("com.ibireme.text.render", attr);
  27. }
  28. } else {
  29. for (NSUInteger i = 0; i < queueCount; i++) {
  30. queues[i] = dispatch_queue_create("com.ibireme.text.render", DISPATCH_QUEUE_SERIAL);
  31. dispatch_set_target_queue(queues[i], dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
  32. }
  33. }
  34. });
  35. uint32_t cur = (uint32_t)OSAtomicIncrement32(&counter);
  36. return queues[(cur) % queueCount];
  37. #undef MAX_QUEUE_COUNT
  38. }
  39. static dispatch_queue_t YYTextAsyncLayerGetReleaseQueue() {
  40. #ifdef YYDispatchQueuePool_h
  41. return YYDispatchQueueGetForQOS(NSQualityOfServiceDefault);
  42. #else
  43. return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
  44. #endif
  45. }
  46. /// a thread safe incrementing counter.
  47. @interface _YYTextSentinel : NSObject
  48. /// Returns the current value of the counter.
  49. @property (atomic, readonly) int32_t value;
  50. /// Increase the value atomically. @return The new value.
  51. - (int32_t)increase;
  52. @end
  53. @implementation _YYTextSentinel {
  54. int32_t _value;
  55. }
  56. - (int32_t)value {
  57. return _value;
  58. }
  59. - (int32_t)increase {
  60. return OSAtomicIncrement32(&_value);
  61. }
  62. @end
  63. @implementation YYTextAsyncLayerDisplayTask
  64. @end
  65. @implementation YYTextAsyncLayer {
  66. _YYTextSentinel *_sentinel;
  67. }
  68. #pragma mark - Override
  69. + (id)defaultValueForKey:(NSString *)key {
  70. if ([key isEqualToString:@"displaysAsynchronously"]) {
  71. return @(YES);
  72. } else {
  73. return [super defaultValueForKey:key];
  74. }
  75. }
  76. - (instancetype)init {
  77. self = [super init];
  78. static CGFloat scale; //global
  79. static dispatch_once_t onceToken;
  80. dispatch_once(&onceToken, ^{
  81. scale = [UIScreen mainScreen].scale;
  82. });
  83. self.contentsScale = scale;
  84. _sentinel = [_YYTextSentinel new];
  85. _displaysAsynchronously = YES;
  86. return self;
  87. }
  88. - (void)dealloc {
  89. [_sentinel increase];
  90. }
  91. - (void)setNeedsDisplay {
  92. [self _cancelAsyncDisplay];
  93. [super setNeedsDisplay];
  94. }
  95. - (void)display {
  96. super.contents = super.contents;
  97. [self _displayAsync:_displaysAsynchronously];
  98. }
  99. #pragma mark - Private
  100. - (void)_displayAsync:(BOOL)async {
  101. __strong id<YYTextAsyncLayerDelegate> delegate = (id)self.delegate;
  102. YYTextAsyncLayerDisplayTask *task = [delegate newAsyncDisplayTask];
  103. if (!task.display) {
  104. if (task.willDisplay) task.willDisplay(self);
  105. self.contents = nil;
  106. if (task.didDisplay) task.didDisplay(self, YES);
  107. return;
  108. }
  109. if (async) {
  110. if (task.willDisplay) task.willDisplay(self);
  111. _YYTextSentinel *sentinel = _sentinel;
  112. int32_t value = sentinel.value;
  113. BOOL (^isCancelled)() = ^BOOL() {
  114. return value != sentinel.value;
  115. };
  116. CGSize size = self.bounds.size;
  117. BOOL opaque = self.opaque;
  118. CGFloat scale = self.contentsScale;
  119. CGColorRef backgroundColor = (opaque && self.backgroundColor) ? CGColorRetain(self.backgroundColor) : NULL;
  120. if (size.width < 1 || size.height < 1) {
  121. CGImageRef image = (__bridge_retained CGImageRef)(self.contents);
  122. self.contents = nil;
  123. if (image) {
  124. dispatch_async(YYTextAsyncLayerGetReleaseQueue(), ^{
  125. CFRelease(image);
  126. });
  127. }
  128. if (task.didDisplay) task.didDisplay(self, YES);
  129. CGColorRelease(backgroundColor);
  130. return;
  131. }
  132. dispatch_async(YYTextAsyncLayerGetDisplayQueue(), ^{
  133. if (isCancelled()) {
  134. CGColorRelease(backgroundColor);
  135. return;
  136. }
  137. UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
  138. CGContextRef context = UIGraphicsGetCurrentContext();
  139. if (opaque) {
  140. CGContextSaveGState(context); {
  141. if (!backgroundColor || CGColorGetAlpha(backgroundColor) < 1) {
  142. CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
  143. CGContextAddRect(context, CGRectMake(0, 0, size.width * scale, size.height * scale));
  144. CGContextFillPath(context);
  145. }
  146. if (backgroundColor) {
  147. CGContextSetFillColorWithColor(context, backgroundColor);
  148. CGContextAddRect(context, CGRectMake(0, 0, size.width * scale, size.height * scale));
  149. CGContextFillPath(context);
  150. }
  151. } CGContextRestoreGState(context);
  152. CGColorRelease(backgroundColor);
  153. }
  154. task.display(context, size, isCancelled);
  155. if (isCancelled()) {
  156. UIGraphicsEndImageContext();
  157. dispatch_async(dispatch_get_main_queue(), ^{
  158. if (task.didDisplay) task.didDisplay(self, NO);
  159. });
  160. return;
  161. }
  162. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  163. UIGraphicsEndImageContext();
  164. if (isCancelled()) {
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. if (task.didDisplay) task.didDisplay(self, NO);
  167. });
  168. return;
  169. }
  170. dispatch_async(dispatch_get_main_queue(), ^{
  171. if (isCancelled()) {
  172. if (task.didDisplay) task.didDisplay(self, NO);
  173. } else {
  174. self.contents = (__bridge id)(image.CGImage);
  175. if (task.didDisplay) task.didDisplay(self, YES);
  176. }
  177. });
  178. });
  179. } else {
  180. [_sentinel increase];
  181. if (task.willDisplay) task.willDisplay(self);
  182. // UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, self.contentsScale);
  183. // CGContextRef context = UIGraphicsGetCurrentContext();
  184. // if (self.opaque) {
  185. // CGSize size = self.bounds.size;
  186. // size.width *= self.contentsScale;
  187. // size.height *= self.contentsScale;
  188. // CGContextSaveGState(context); {
  189. // if (!self.backgroundColor || CGColorGetAlpha(self.backgroundColor) < 1) {
  190. // CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
  191. // CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height));
  192. // CGContextFillPath(context);
  193. // }
  194. // if (self.backgroundColor) {
  195. // CGContextSetFillColorWithColor(context, self.backgroundColor);
  196. // CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height));
  197. // CGContextFillPath(context);
  198. // }
  199. // } CGContextRestoreGState(context);
  200. // }
  201. // task.display(context, self.bounds.size, ^{return NO;});
  202. // UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  203. // UIGraphicsEndImageContext();
  204. // self.contents = (__bridge id)(image.CGImage);
  205. UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
  206. format.opaque = self.opaque;
  207. format.scale = self.contentsScale;
  208. UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:self.bounds.size format:format];
  209. UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
  210. CGContextRef context = rendererContext.CGContext;
  211. if (self.opaque) {
  212. CGSize size = self.bounds.size;
  213. size.width *= self.contentsScale;
  214. size.height *= self.contentsScale;
  215. CGContextSaveGState(context); {
  216. if (!self.backgroundColor || CGColorGetAlpha(self.backgroundColor) < 1) {
  217. CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
  218. CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height));
  219. CGContextFillPath(context);
  220. }
  221. if (self.backgroundColor) {
  222. CGContextSetFillColorWithColor(context, self.backgroundColor);
  223. CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height));
  224. CGContextFillPath(context);
  225. }
  226. } CGContextRestoreGState(context);
  227. }
  228. task.display(context, self.bounds.size, ^{return NO;});
  229. }];
  230. self.contents = (__bridge id)(image.CGImage);
  231. if (task.didDisplay) task.didDisplay(self, YES);
  232. }
  233. }
  234. - (void)_cancelAsyncDisplay {
  235. [_sentinel increase];
  236. }
  237. @end