YYSpriteSheetImage.m 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // YYSpriteImage.m
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 15/4/21.
  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 "YYSpriteSheetImage.h"
  12. @implementation YYSpriteSheetImage
  13. - (instancetype)initWithSpriteSheetImage:(UIImage *)image
  14. contentRects:(NSArray *)contentRects
  15. frameDurations:(NSArray *)frameDurations
  16. loopCount:(NSUInteger)loopCount {
  17. if (!image.CGImage) return nil;
  18. if (contentRects.count < 1 || frameDurations.count < 1) return nil;
  19. if (contentRects.count != frameDurations.count) return nil;
  20. self = [super initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation];
  21. if (!self) return nil;
  22. _contentRects = contentRects.copy;
  23. _frameDurations = frameDurations.copy;
  24. _loopCount = loopCount;
  25. return self;
  26. }
  27. - (CGRect)contentsRectForCALayerAtIndex:(NSUInteger)index {
  28. CGRect layerRect = CGRectMake(0, 0, 1, 1);
  29. if (index >= _contentRects.count) return layerRect;
  30. CGSize imageSize = self.size;
  31. CGRect rect = [self animatedImageContentsRectAtIndex:index];
  32. if (imageSize.width > 0.01 && imageSize.height > 0.01) {
  33. layerRect.origin.x = rect.origin.x / imageSize.width;
  34. layerRect.origin.y = rect.origin.y / imageSize.height;
  35. layerRect.size.width = rect.size.width / imageSize.width;
  36. layerRect.size.height = rect.size.height / imageSize.height;
  37. layerRect = CGRectIntersection(layerRect, CGRectMake(0, 0, 1, 1));
  38. if (CGRectIsNull(layerRect) || CGRectIsEmpty(layerRect)) {
  39. layerRect = CGRectMake(0, 0, 1, 1);
  40. }
  41. }
  42. return layerRect;
  43. }
  44. #pragma mark @protocol YYAnimatedImage
  45. - (NSUInteger)animatedImageFrameCount {
  46. return _contentRects.count;
  47. }
  48. - (NSUInteger)animatedImageLoopCount {
  49. return _loopCount;
  50. }
  51. - (NSUInteger)animatedImageBytesPerFrame {
  52. return 0;
  53. }
  54. - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
  55. return self;
  56. }
  57. - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index {
  58. if (index >= _frameDurations.count) return 0;
  59. return ((NSNumber *)_frameDurations[index]).doubleValue;
  60. }
  61. - (CGRect)animatedImageContentsRectAtIndex:(NSUInteger)index {
  62. if (index >= _contentRects.count) return CGRectZero;
  63. return ((NSValue *)_contentRects[index]).CGRectValue;
  64. }
  65. @end