SDWaitingView.m 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // SDWaitingView.m
  3. // SDPhotoBrowser
  4. //
  5. // Created by aier on 15-2-6.
  6. // Copyright (c) 2015年 GSD. All rights reserved.
  7. //
  8. #import "SDWaitingView.h"
  9. //// 图片下载进度指示器背景色
  10. //#define SDWaitingViewBackgroundColor [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7]
  11. //
  12. //// 图片下载进度指示器内部控件间的间距
  13. //
  14. //#define SDWaitingViewItemMargin 10
  15. @implementation SDWaitingView
  16. - (id)initWithFrame:(CGRect)frame
  17. {
  18. self = [super initWithFrame:frame];
  19. if (self) {
  20. self.backgroundColor = SDWaitingViewBackgroundColor;
  21. self.layer.cornerRadius = 5;
  22. self.clipsToBounds = YES;
  23. self.mode = SDWaitingViewModeLoopDiagram;
  24. }
  25. return self;
  26. }
  27. - (void)setProgress:(CGFloat)progress
  28. {
  29. _progress = progress;
  30. // NSLog(@"%@",[NSThread currentThread]);
  31. //将重绘操作放在主线程,解决自动布局控制台报错的问题
  32. dispatch_async(dispatch_get_main_queue(), ^{
  33. [self setNeedsDisplay];
  34. if (progress >= 1) {
  35. [self removeFromSuperview];
  36. }
  37. });
  38. }
  39. - (void)drawRect:(CGRect)rect
  40. {
  41. CGContextRef ctx = UIGraphicsGetCurrentContext();
  42. CGFloat xCenter = rect.size.width * 0.5;
  43. CGFloat yCenter = rect.size.height * 0.5;
  44. [[UIColor whiteColor] set];
  45. switch (self.mode) {
  46. case SDWaitingViewModePieDiagram:
  47. {
  48. CGFloat radius = MIN(rect.size.width * 0.5, rect.size.height * 0.5) - SDWaitingViewItemMargin;
  49. CGFloat w = radius * 2 + SDWaitingViewItemMargin;
  50. CGFloat h = w;
  51. CGFloat x = (rect.size.width - w) * 0.5;
  52. CGFloat y = (rect.size.height - h) * 0.5;
  53. CGContextAddEllipseInRect(ctx, CGRectMake(x, y, w, h));
  54. CGContextFillPath(ctx);
  55. [SDWaitingViewBackgroundColor set];
  56. CGContextMoveToPoint(ctx, xCenter, yCenter);
  57. CGContextAddLineToPoint(ctx, xCenter, 0);
  58. CGFloat to = - M_PI * 0.5 + self.progress * M_PI * 2 + 0.001; // 初始值
  59. CGContextAddArc(ctx, xCenter, yCenter, radius, - M_PI * 0.5, to, 1);
  60. CGContextClosePath(ctx);
  61. CGContextFillPath(ctx);
  62. }
  63. break;
  64. default:
  65. {
  66. CGContextSetLineWidth(ctx, 15);
  67. CGContextSetLineCap(ctx, kCGLineCapRound);
  68. CGFloat to = - M_PI * 0.5 + self.progress * M_PI * 2 + 0.05; // 初始值0.05
  69. CGFloat radius = MIN(rect.size.width, rect.size.height) * 0.5 - SDWaitingViewItemMargin;
  70. CGContextAddArc(ctx, xCenter, yCenter, radius, - M_PI * 0.5, to, 0);
  71. CGContextStrokePath(ctx);
  72. }
  73. break;
  74. }
  75. }
  76. @end