溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

iOS如何實現(xiàn)帶指引線的餅狀圖效果

發(fā)布時間:2021-05-24 11:58:04 來源:億速云 閱讀:316 作者:小新 欄目:移動開發(fā)

這篇文章主要介紹了iOS如何實現(xiàn)帶指引線的餅狀圖效果,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

效果圖

先上圖(做出來的效果就是下圖的樣子)

iOS如何實現(xiàn)帶指引線的餅狀圖效果

1.效果圖-w220

圖中不論每個扇形多小,都可以從指引線處將指引的數(shù)據(jù)分割開來,不會重疊。

第一步

需要給圖中數(shù)據(jù)做個模型

@interface DVFoodPieModel : NSObject
/**
 名稱
 */
@property (copy, nonatomic) NSString *name;

/**
 數(shù)值
 */
@property (assign, nonatomic) CGFloat value;

/**
 比例
 */
@property (assign, nonatomic) CGFloat rate;
@end

第二步

現(xiàn)在先把餅圖中間的圓形做出來,這個沒有什么難度,直接貼代碼

在.h文件中

@interface DVPieCenterView : UIView 
@property (strong, nonatomic) UILabel *nameLabel; 
@end

在.m文件中

@interface DVPieCenterView ()
@property (strong, nonatomic) UIView *centerView;
@end
@implementation DVPieCenterView
- (instancetype)initWithFrame:(CGRect)frame {
 if (self = [super initWithFrame:frame]) {
  self.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.4];
  UIView *centerView = [[UIView alloc] init];
  centerView.backgroundColor = [UIColor whiteColor];
  [self addSubview:centerView];
  self.centerView = centerView;
  UILabel *nameLabel = [[UILabel alloc] init];
  nameLabel.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
  nameLabel.font = [UIFont systemFontOfSize:18];
  nameLabel.textAlignment = NSTextAlignmentCenter;
  self.nameLabel = nameLabel;
  [centerView addSubview:nameLabel];
 }
 return self;
}


- (void)layoutSubviews {
 [super layoutSubviews];
 self.layer.cornerRadius = self.frame.size.width * 0.5;
 self.layer.masksToBounds = true;
 self.centerView.frame = CGRectMake(6, 6, self.frame.size.width - 6 * 2, self.frame.size.height - 6 * 2);
 self.centerView.layer.cornerRadius = self.centerView.frame.size.width * 0.5;
 self.centerView.layer.masksToBounds = true;
 self.nameLabel.frame = self.centerView.bounds;
}

暴露的只有.h文件中的namelabel,需要中間顯示文字時,給nameLabel的text賦值就好了

第三步

現(xiàn)在就創(chuàng)建一個繼承UIView的視圖,用來畫餅狀圖和指引線以及數(shù)據(jù)

在.h文件中需要有數(shù)據(jù)數(shù)組,還有中間顯示的文字,以及一個draw方法(draw方法純屬個人習(xí)慣,在數(shù)據(jù)全部賦值完成后,調(diào)用該方法進行繪畫)

@interface DVPieChart : UIView
/**
 數(shù)據(jù)數(shù)組
 */
@property (strong, nonatomic) NSArray *dataArray;
/**
 標(biāo)題
 */
@property (copy, nonatomic) NSString *title;
/**
 繪制方法
 */
- (void)draw;
@end

在調(diào)用draw方法前應(yīng)確定數(shù)據(jù)全部賦值完成,繪制工作其實是在- (void)drawRect:(CGRect)rect方法中完成的,所以.h文件中的draw方法只是來調(diào)用系統(tǒng)方法的

在.m文件中,draw方法的實現(xiàn)

- (void)draw {
 [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
 [self setNeedsDisplay];
}

[self setNeedsDisplay];就是來調(diào)用drawRect方法的

[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];這個方法是用來移除添加到pieChart上的centerView,不然每次重繪時都會再次添加一個centerView

下面就是drawRect方法的實現(xiàn)

首先需要確定圓的半徑,中心點和起始點

CGFloat min = self.bounds.size.width > self.bounds.size.height ? self.bounds.size.height : self.bounds.size.width;
CGPoint center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
CGFloat radius = min * 0.5 - CHART_MARGIN;
CGFloat start = 0;
CGFloat angle = 0;
CGFloat end = start;

CHART_MARGIN是自己定義的一個宏,圓不能讓視圖的邊形成切線,在此我把CHART_MARGIN設(shè)定為60
* 根據(jù)產(chǎn)品的需求,當(dāng)請求回來的數(shù)據(jù)為空時,顯示一個純色的圓,不畫指引線,所以在drawRect中分兩種情況來實現(xiàn)

```objc
if (self.dataArray.count == 0) {

} else {

}
```
* 當(dāng)dataArray的長度為0時

```objc
if (self.dataArray.count == 0) {
 
 end = start + M_PI * 2;
 
 UIColor *color = COLOR_ARRAY.firstObject;
 
 UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:start endAngle:end clockwise:true];
 
 [color set];
 
 //添加一根線到圓心
 [path addLineToPoint:center];
 [path fill];
 
}
```
> COLOR_ARRAY是自己設(shè)定的一個宏定義,產(chǎn)品要求的餅圖份數(shù)是6份,每份顏色一定,所以做一個宏定義存儲一下(做成變量都是可以的,看自己代碼風(fēng)格)

``` objc
#define COLOR_ARRAY @[\

[UIColor colorWithRed:251/255.0 green:166.9/255.0 blue:96.5/255.0 alpha:1],
[UIColor colorWithRed:151.9/255.0 green:188/255.0 blue:95.8/255.0 alpha:1],
[UIColor colorWithRed:245/255.0 green:94/255.0 blue:102/255.0 alpha:1],
[UIColor colorWithRed:29/255.0 green:140/255.0 blue:140/255.0 alpha:1],
[UIColor colorWithRed:121/255.0 green:113/255.0 blue:199/255.0 alpha:1],
[UIColor colorWithRed:16/255.0 green:149/255.0 blue:224/255.0 alpha:1]
]
```

* 當(dāng)dataArray的長度不為0時

```objc

for (int i = 0; i < self.dataArray.count; i++) {
 DVFoodPieModel *model = self.dataArray[i];
 CGFloat percent = model.rate;
 UIColor *color = COLOR_ARRAY[i % 6];
 start = end;
 angle = percent * M_PI * 2;
 end = start + angle;
 UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:start endAngle:end clockwise:true];
 [color set];
 //添加一根線到圓心
 [path addLineToPoint:center];
 [path fill];
}
```

在else中這么做,就能繪制出各個扇形

* 在扇形繪畫出來后,添加centerView
```objc
// 在中心添加label
DVPieCenterView *centerView = [[DVPieCenterView alloc] init];
centerView.frame = CGRectMake(0, 0, 80, 80);
CGRect frame = centerView.frame;
frame.origin = CGPointMake(self.frame.size.width * 0.5 - frame.size.width * 0.5, self.frame.size.height * 0.5 - frame.size.width * 0.5);
centerView.frame = frame;
centerView.nameLabel.text = self.title;
[self addSubview:centerView];
```

第四步,繪畫指引線和數(shù)據(jù)

繪制指引線,需要在畫扇形時就確定幾個數(shù)據(jù),并根據(jù)這幾種數(shù)據(jù)進行繪制

  • 各個扇形圓弧的中心點

  • 指引線的重點(效果圖中有圓點的位置)

// 獲取弧度的中心角度
CGFloat radianCenter = (start + end) * 0.5;
// 獲取指引線的終點
CGFloat lineStartX = self.frame.size.width * 0.5 + radius * cos(radianCenter);
CGFloat lineStartY = self.frame.size.height * 0.5 + radius * sin(radianCenter);
CGPoint point = CGPointMake(lineStartX, lineStartY);

因為這個圖剛剛做出來時是有重疊的,按產(chǎn)品需求進行更改,所以起的變量名稱會有些歧義,不方便改了,我只能做好注釋,大家以注釋為準(zhǔn)

如果按順序進行繪制的話,那么很難讓指引線的位置不重疊,所以從中間的一個數(shù)據(jù)先進行繪制,然后在繪制中間數(shù)據(jù)兩側(cè)的數(shù)據(jù)

那么,現(xiàn)在需要將上面需要確定的數(shù)據(jù)依次添加到一個數(shù)組中

例:原數(shù)據(jù)為@[@1, @2, @3, @4, @5, @6]

畫指引線時則需要數(shù)據(jù)這樣來弄@[@3, @2, @1, @4, @5, @6]

所以for循環(huán)中應(yīng)該改成這個樣子

注意,數(shù)據(jù)變更順序了之后,繪制時模型數(shù)據(jù)和顏色數(shù)據(jù)也需要變更順序

首先聲明兩個變量

@interface DVPieChart ()
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSMutableArray *colorArray;
@end

else中變成下面這個樣子

NSMutableArray *pointArray = [NSMutableArray array];
NSMutableArray *centerArray = [NSMutableArray array];
self.modelArray = [NSMutableArray array];
self.colorArray = [NSMutableArray array];
for (int i = 0; i < self.dataArray.count; i++) {
 DVFoodPieModel *model = self.dataArray[i];
 CGFloat percent = model.rate;
 UIColor *color = COLOR_ARRAY[i];
 start = end;
 angle = percent * M_PI * 2;
 end = start + angle;
 UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:start endAngle:end clockwise:true]; 
 [color set];
 //添加一根線到圓心
 [path addLineToPoint:center];
 [path fill];
 // 獲取弧度的中心角度
 CGFloat radianCenter = (start + end) * 0.5;
 // 獲取指引線的終點
 CGFloat lineStartX = self.frame.size.width * 0.5 + radius * cos(radianCenter);
 CGFloat lineStartY = self.frame.size.height * 0.5 + radius * sin(radianCenter);
 CGPoint point = CGPointMake(lineStartX, lineStartY);
 if (i <= self.dataArray.count / 2 - 1) {
  [pointArray insertObject:[NSValue valueWithCGPoint:point] atIndex:0];
  [centerArray insertObject:[NSNumber numberWithFloat:radianCenter] atIndex:0];
  [self.modelArray insertObject:model atIndex:0];
  [self.colorArray insertObject:color atIndex:0];
 } else {
  [pointArray addObject:[NSValue valueWithCGPoint:point]];
  [centerArray addObject:[NSNumber numberWithFloat:radianCenter]];
  [self.modelArray addObject:model];
  [self.colorArray addObject:color];
 }
}

for循環(huán)中確定了需要的數(shù)據(jù):

pointArray、centerArray、self.modelArray、self.colorArray

根據(jù)上面確定的數(shù)據(jù)來繪出指引線,邏輯比較復(fù)雜,寫一個方法來繪制

- (void)drawLineWithPointArray:(NSArray *)pointArray centerArray:(NSArray *)centerArray

在for循環(huán)外調(diào)用

// 通過pointArray和centerArray繪制指引線
[self drawLineWithPointArray:pointArray centerArray:centerArray];

第五步

方法內(nèi)部實現(xiàn)

需要確定的數(shù)據(jù)都有:

1.指引線長度

2.指引線起點、終點、轉(zhuǎn)折點

3.指引線數(shù)據(jù)所占的rect范圍(用于確定繪制下一個的時候是否有重疊)

下面直接貼出代碼實現(xiàn),注意看注釋,我就不在代碼外再寫一遍了

- (void)drawLineWithPointArray:(NSArray *)pointArray centerArray:(NSArray *)centerArray {
 // 記錄每一個指引線包括數(shù)據(jù)所占用位置的和(總體位置)
 CGRect rect = CGRectZero;
 // 用于計算指引線長度
 CGFloat width = self.bounds.size.width * 0.5;
 for (int i = 0; i < pointArray.count; i++) {
  // 取出數(shù)據(jù)
  NSValue *value = pointArray[i];
  // 每個圓弧中心店的位置
  CGPoint point = value.CGPointValue;
  // 每個圓弧中心點的角度
  CGFloat radianCenter = [centerArray[i] floatValue];
  // 顏色(繪制數(shù)據(jù)時要用)
  UIColor *color = self.colorArray[i % 6];
  // 模型數(shù)據(jù)(繪制數(shù)據(jù)時要用)
  DVFoodPieModel *model = self.modelArray[i];
  // 模型的數(shù)據(jù)
  NSString *name = model.name;
  NSString *number = [NSString stringWithFormat:@"%.2f%%", model.rate * 100];

  // 圓弧中心點的x值和y值
  CGFloat x = point.x;
  CGFloat y = point.y;
  
  // 指引線終點的位置(x, y)
  CGFloat startX = x + 10 * cos(radianCenter);
  CGFloat startY = y + 10 * sin(radianCenter);
  
  // 指引線轉(zhuǎn)折點的位置(x, y)
  CGFloat breakPointX = x + 20 * cos(radianCenter);
  CGFloat breakPointY = y + 20 * sin(radianCenter);
  
  // 轉(zhuǎn)折點到中心豎線的垂直長度(為什么+20, 在實際做出的效果中,有的轉(zhuǎn)折線很丑,+20為了美化)
  CGFloat margin = fabs(width - breakPointX) + 20;
  
  // 指引線長度
  CGFloat lineWidth = width - margin;
  
  // 指引線起點(x, y)
  CGFloat endX;
  CGFloat endY;
  
  // 繪制文字和數(shù)字時,所占的size(width和height)
  // width使用lineWidth更好,我這么寫固定值是為了達到產(chǎn)品要求
  CGFloat numberWidth = 80.f;
  CGFloat numberHeight = 15.f;
  
  CGFloat titleWidth = numberWidth;
  CGFloat titleHeight = numberHeight;
  
  // 繪制文字和數(shù)字時的起始位置(x, y)與上面的合并起來就是frame
  CGFloat numberX;// = breakPointX;
  CGFloat numberY = breakPointY - numberHeight;
  
  CGFloat titleX = breakPointX;
  CGFloat titleY = breakPointY + 2;
  
  
  // 文本段落屬性(繪制文字和數(shù)字時需要)
  NSMutableParagraphStyle * paragraph = [[NSMutableParagraphStyle alloc]init];
  // 文字靠右
  paragraph.alignment = NSTextAlignmentRight;
  
  // 判斷x位置,確定在指引線向左還是向右繪制
  // 根據(jù)需要變更指引線的起始位置
  // 變更文字和數(shù)字的位置
  if (x <= width) { // 在左邊
   
   endX = 10;
   endY = breakPointY;
   
   // 文字靠左
   paragraph.alignment = NSTextAlignmentLeft;
   
   numberX = endX;
   titleX = endX;
   
  } else { // 在右邊
   
   endX = self.bounds.size.width - 10;
   endY = breakPointY;
   
   numberX = endX - numberWidth;
   titleX = endX - titleWidth;
  }
  
  
  if (i != 0) {
   
   // 當(dāng)i!=0時,就需要計算位置總和(方法開始出的rect)與rect1(將進行繪制的位置)是否有重疊
   CGRect rect1 = CGRectMake(numberX, numberY, numberWidth, titleY + titleHeight - numberY);
   
   CGFloat margin = 0;
   
   if (CGRectIntersectsRect(rect, rect1)) {
    // 兩個面積重疊
    // 三種情況
    // 1. 壓上面
    // 2. 壓下面
    // 3. 包含
    // 通過計算讓面積重疊的情況消除
    if (CGRectContainsRect(rect, rect1)) {// 包含
     
     if (i % self.dataArray.count <= self.dataArray.count * 0.5 - 1) {
      // 將要繪制的位置在總位置偏上
      margin = CGRectGetMaxY(rect1) - rect.origin.y;
      endY -= margin;
     } else {
      // 將要繪制的位置在總位置偏下
      margin = CGRectGetMaxY(rect) - rect1.origin.y;
      endY += margin;
     }
     
     
    } else { // 相交
     
     if (CGRectGetMaxY(rect1) > rect.origin.y && rect1.origin.y < rect.origin.y) { // 壓在總位置上面
      margin = CGRectGetMaxY(rect1) - rect.origin.y;
      endY -= margin;
      
     } else if (rect1.origin.y < CGRectGetMaxY(rect) && CGRectGetMaxY(rect1) > CGRectGetMaxY(rect)) { // 壓總位置下面
      margin = CGRectGetMaxY(rect) - rect1.origin.y;
      endY += margin;
     }
     
    }
   }
   titleY = endY + 2;
   numberY = endY - numberHeight;
   
   
   // 通過計算得出的將要繪制的位置
   CGRect rect2 = CGRectMake(numberX, numberY, numberWidth, titleY + titleHeight - numberY);
   
   // 把新獲得的rect和之前的rect合并
   if (numberX == rect.origin.x) {
    // 當(dāng)兩個位置在同一側(cè)的時候才需要合并
    if (rect2.origin.y < rect.origin.y) {
     rect = CGRectMake(rect.origin.x, rect2.origin.y, rect.size.width, rect.size.height + rect2.size.height);
    } else {
     rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height + rect2.size.height);
    }
   }
   
  } else {
   rect = CGRectMake(numberX, numberY, numberWidth, titleY + titleHeight - numberY);
  }

  // 重新制定轉(zhuǎn)折點
  if (endX == 10) {
   breakPointX = endX + lineWidth;
  } else {
   breakPointX = endX - lineWidth;
  }
  
  breakPointY = endY;
  //1.獲取上下文
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  //2.繪制路徑
  UIBezierPath *path = [UIBezierPath bezierPath];
  [path moveToPoint:CGPointMake(endX, endY)];
  [path addLineToPoint:CGPointMake(breakPointX, breakPointY)];
  [path addLineToPoint:CGPointMake(startX, startY)];
  CGContextSetLineWidth(ctx, 0.5);
  //設(shè)置顏色
  [color set];
  //3.把繪制的內(nèi)容添加到上下文當(dāng)中
  CGContextAddPath(ctx, path.CGPath);
  //4.把上下文的內(nèi)容顯示到View上(渲染到View的layer)(stroke fill)
  CGContextStrokePath(ctx);

  // 在終點處添加點(小圓點)
  // movePoint,讓轉(zhuǎn)折線指向小圓點中心
  CGFloat movePoint = -2.5;
  UIView *view = [[UIView alloc] init];
  view.backgroundColor = color;
  [self addSubview:view];
  CGRect rect = view.frame;
  rect.size = CGSizeMake(5, 5);
  rect.origin = CGPointMake(startX + movePoint, startY - 2.5);
  view.frame = rect;
  view.layer.cornerRadius = 2.5;
  view.layer.masksToBounds = true;

  //指引線上面的數(shù)字
  [name drawInRect:CGRectMake(numberX, numberY, numberWidth, numberHeight) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:9.0], NSForegroundColorAttributeName:color,NSParagraphStyleAttributeName:paragraph}];
  
  // 指引線下面的title
  [number drawInRect:CGRectMake(titleX, titleY, titleWidth, titleHeight) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:9.0],NSForegroundColorAttributeName:color,NSParagraphStyleAttributeName:paragraph}];
 } 
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“iOS如何實現(xiàn)帶指引線的餅狀圖效果”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

ios
AI