RKCircularProgress.m 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // RKCircularProgress.m
  3. // TestApp
  4. //
  5. // Created by YB007 on 2020/7/7.
  6. // Copyright © 2020 Rookie. All rights reserved.
  7. //
  8. #import "RKCircularProgress.h"
  9. @interface RKCircularProgress()
  10. @end
  11. @implementation RKCircularProgress
  12. - (id)initWithFrame:(CGRect)frame {
  13. if (self = [super initWithFrame:frame]) {
  14. self.backgroundColor = UIColor.clearColor;
  15. self.layer.cornerRadius = 5;
  16. self.clipsToBounds = YES;
  17. }
  18. return self;
  19. }
  20. - (void)setProgress:(CGFloat)progress {
  21. _progress = progress;
  22. dispatch_async(dispatch_get_main_queue(), ^{
  23. // if (progress >= 1.0) {
  24. // [self removeFromSuperview];
  25. // } else {
  26. [self setNeedsDisplay];
  27. // }
  28. });
  29. }
  30. - (void)setCenterProgressText:(NSString *)text withAttributes:(NSDictionary *)attributes {
  31. CGFloat xCenter = self.frame.size.width * 0.5;
  32. CGFloat yCenter = self.frame.size.height * 0.5;
  33. CGSize strSize = [text sizeWithAttributes:attributes];
  34. CGFloat strX = xCenter - strSize.width * 0.5;
  35. CGFloat strY = yCenter - strSize.height * 0.5;
  36. [text drawAtPoint:CGPointMake(strX, strY) withAttributes:attributes];
  37. }
  38. // 清除指示器
  39. - (void)dismiss {
  40. self.progress = 1.0;
  41. }
  42. - (void)drawRect:(CGRect)rect {
  43. CGContextRef ctx = UIGraphicsGetCurrentContext();
  44. CGFloat xCenter = rect.size.width * 0.5;
  45. CGFloat yCenter = rect.size.height * 0.5;
  46. [[UIColor whiteColor] set];
  47. CGContextSetLineWidth(ctx, 2);
  48. CGContextSetLineCap(ctx, kCGLineCapRound);
  49. CGFloat to = -M_PI * 0.5 + self.progress * M_PI * 2 + 0.00; // 初始值0.01
  50. CGFloat radius = MIN(rect.size.width, rect.size.height) * 0.2;
  51. CGContextAddArc(ctx, xCenter, yCenter, radius, -M_PI * 0.5, to, 0);
  52. CGContextStrokePath(ctx);
  53. //进度数字
  54. NSString *progressStr = [NSString stringWithFormat:@"%.0f%%", self.progress * 100];
  55. NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
  56. attributes[NSFontAttributeName] = [UIFont systemFontOfSize:MIN(rect.size.width, rect.size.height)*0.1];
  57. attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
  58. [self setCenterProgressText:progressStr withAttributes:attributes];
  59. }
  60. @end