PieView.m 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. //
  2. // PieView.m
  3. // 饼状图
  4. //
  5. // Created by mac on 14-3-31.
  6. // Copyright (c) 2014年 mac. All rights reserved.
  7. //
  8. #import "PieView.h"
  9. @implementation PieView
  10. @synthesize delegate;
  11. @synthesize datasource;
  12. //初始化
  13. - (id)initWithFrame:(CGRect)frame
  14. {
  15. self = [super initWithFrame:frame];
  16. if (self) {
  17. self.backgroundColor = [UIColor clearColor];
  18. self.layer.shadowColor = [[UIColor grayColor] CGColor];
  19. self.layer.shadowOffset = CGSizeMake(3, 3);
  20. self.layer.shadowRadius = 1.5;
  21. self.layer.shadowOpacity = 0.9;
  22. }
  23. return self;
  24. }
  25. //加载视图
  26. -(void)reloadData
  27. {
  28. [self setNeedsDisplay];
  29. }
  30. //绘制
  31. - (void)drawRect:(CGRect)rect
  32. {
  33. //prepare
  34. CGContextRef context = UIGraphicsGetCurrentContext();
  35. CGFloat theHalf = rect.size.width/2;
  36. CGFloat lineWidth = theHalf;
  37. if ([self.delegate respondsToSelector:@selector(centerCircleRadius)])
  38. {
  39. lineWidth -= [self.delegate centerCircleRadius];
  40. NSAssert(lineWidth <= theHalf, @"wrong circle radius");
  41. }
  42. CGFloat radius = theHalf-lineWidth/2;
  43. CGFloat centerX = theHalf;
  44. CGFloat centerY = rect.size.height/2;
  45. //drawing
  46. double sum = 0.0f;
  47. int slicesCount = [self.datasource numberOfSlicesInPieChartView:self];
  48. for (int i = 0; i < slicesCount; i++)
  49. {
  50. sum += [self.datasource pieChartView:self valueForSliceAtIndex:i];
  51. }
  52. float startAngle = - M_PI_2;
  53. float endAngle = 0.0f;
  54. for (int i = 0; i < slicesCount; i++)
  55. {
  56. double value = [self.datasource pieChartView:self valueForSliceAtIndex:i];
  57. endAngle = startAngle + M_PI*2*value/sum;
  58. CGContextAddArc(context, centerX, centerY, radius, startAngle, endAngle, false);
  59. UIColor *drawColor = [self.datasource pieChartView:self colorForSliceAtIndex:i];
  60. CGContextSetStrokeColorWithColor(context, drawColor.CGColor);
  61. CGContextSetLineWidth(context, lineWidth);
  62. CGContextStrokePath(context);
  63. startAngle += M_PI*2*value/sum;
  64. }
  65. }
  66. @end