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

1.效果圖-w220
圖中不論每個扇形多小,都可以從指引線處將指引的數據分割開來,不會重疊。
第一步
需要給圖中數據做個模型
@interface DVFoodPieModel : NSObject /** 名稱 */ @property (copy, nonatomic) NSString *name; /** 數值 */ @property (assign, nonatomic) CGFloat value; /** 比例 */ @property (assign, nonatomic) CGFloat rate; @end
第二步
現在先把餅圖中間的圓形做出來,這個沒有什么難度,直接貼代碼
在.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賦值就好了
第三步
現在就創建一個繼承UIView的視圖,用來畫餅狀圖和指引線以及數據
在.h文件中需要有數據數組,還有中間顯示的文字,以及一個draw方法(draw方法純屬個人習慣,在數據全部賦值完成后,調用該方法進行繪畫)
@interface DVPieChart : UIView /** 數據數組 */ @property (strong, nonatomic) NSArray *dataArray; /** 標題 */ @property (copy, nonatomic) NSString *title; /** 繪制方法 */ - (void)draw; @end
在調用draw方法前應確定數據全部賦值完成,繪制工作其實是在- (void)drawRect:(CGRect)rect方法中完成的,所以.h文件中的draw方法只是來調用系統方法的
在.m文件中,draw方法的實現
- (void)draw {
[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self setNeedsDisplay];
}[self setNeedsDisplay];就是來調用drawRect方法的
[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];這個方法是用來移除添加到pieChart上的centerView,不然每次重繪時都會再次添加一個centerView
下面就是drawRect方法的實現
首先需要確定圓的半徑,中心點和起始點
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設定為60
* 根據產品的需求,當請求回來的數據為空時,顯示一個純色的圓,不畫指引線,所以在drawRect中分兩種情況來實現
```objc
if (self.dataArray.count == 0) {
} else {
}
```
* 當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是自己設定的一個宏定義,產品要求的餅圖份數是6份,每份顏色一定,所以做一個宏定義存儲一下(做成變量都是可以的,看自己代碼風格)
``` 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]
]
```
* 當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]; ```
第四步,繪畫指引線和數據
繪制指引線,需要在畫扇形時就確定幾個數據,并根據這幾種數據進行繪制
各個扇形圓弧的中心點
指引線的重點(效果圖中有圓點的位置)
// 獲取弧度的中心角度 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);
因為這個圖剛剛做出來時是有重疊的,按產品需求進行更改,所以起的變量名稱會有些歧義,不方便改了,我只能做好注釋,大家以注釋為準
如果按順序進行繪制的話,那么很難讓指引線的位置不重疊,所以從中間的一個數據先進行繪制,然后在繪制中間數據兩側的數據
那么,現在需要將上面需要確定的數據依次添加到一個數組中
例:原數據為@[@1, @2, @3, @4, @5, @6]
畫指引線時則需要數據這樣來弄@[@3, @2, @1, @4, @5, @6]
所以for循環中應該改成這個樣子
注意,數據變更順序了之后,繪制時模型數據和顏色數據也需要變更順序
首先聲明兩個變量
@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循環中確定了需要的數據:
pointArray、centerArray、self.modelArray、self.colorArray
根據上面確定的數據來繪出指引線,邏輯比較復雜,寫一個方法來繪制
- (void)drawLineWithPointArray:(NSArray *)pointArray centerArray:(NSArray *)centerArray
在for循環外調用
// 通過pointArray和centerArray繪制指引線 [self drawLineWithPointArray:pointArray centerArray:centerArray];
第五步
方法內部實現
需要確定的數據都有:
1.指引線長度
2.指引線起點、終點、轉折點
3.指引線數據所占的rect范圍(用于確定繪制下一個的時候是否有重疊)
下面直接貼出代碼實現,注意看注釋,我就不在代碼外再寫一遍了
- (void)drawLineWithPointArray:(NSArray *)pointArray centerArray:(NSArray *)centerArray {
// 記錄每一個指引線包括數據所占用位置的和(總體位置)
CGRect rect = CGRectZero;
// 用于計算指引線長度
CGFloat width = self.bounds.size.width * 0.5;
for (int i = 0; i < pointArray.count; i++) {
// 取出數據
NSValue *value = pointArray[i];
// 每個圓弧中心店的位置
CGPoint point = value.CGPointValue;
// 每個圓弧中心點的角度
CGFloat radianCenter = [centerArray[i] floatValue];
// 顏色(繪制數據時要用)
UIColor *color = self.colorArray[i % 6];
// 模型數據(繪制數據時要用)
DVFoodPieModel *model = self.modelArray[i];
// 模型的數據
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);
// 指引線轉折點的位置(x, y)
CGFloat breakPointX = x + 20 * cos(radianCenter);
CGFloat breakPointY = y + 20 * sin(radianCenter);
// 轉折點到中心豎線的垂直長度(為什么+20, 在實際做出的效果中,有的轉折線很丑,+20為了美化)
CGFloat margin = fabs(width - breakPointX) + 20;
// 指引線長度
CGFloat lineWidth = width - margin;
// 指引線起點(x, y)
CGFloat endX;
CGFloat endY;
// 繪制文字和數字時,所占的size(width和height)
// width使用lineWidth更好,我這么寫固定值是為了達到產品要求
CGFloat numberWidth = 80.f;
CGFloat numberHeight = 15.f;
CGFloat titleWidth = numberWidth;
CGFloat titleHeight = numberHeight;
// 繪制文字和數字時的起始位置(x, y)與上面的合并起來就是frame
CGFloat numberX;// = breakPointX;
CGFloat numberY = breakPointY - numberHeight;
CGFloat titleX = breakPointX;
CGFloat titleY = breakPointY + 2;
// 文本段落屬性(繪制文字和數字時需要)
NSMutableParagraphStyle * paragraph = [[NSMutableParagraphStyle alloc]init];
// 文字靠右
paragraph.alignment = NSTextAlignmentRight;
// 判斷x位置,確定在指引線向左還是向右繪制
// 根據需要變更指引線的起始位置
// 變更文字和數字的位置
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) {
// 當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) {
// 當兩個位置在同一側的時候才需要合并
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);
}
// 重新制定轉折點
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);
//設置顏色
[color set];
//3.把繪制的內容添加到上下文當中
CGContextAddPath(ctx, path.CGPath);
//4.把上下文的內容顯示到View上(渲染到View的layer)(stroke fill)
CGContextStrokePath(ctx);
// 在終點處添加點(小圓點)
// movePoint,讓轉折線指向小圓點中心
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;
//指引線上面的數字
[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}];
}
}感謝你能夠認真閱讀完這篇文章,希望小編分享的“iOS如何實現帶指引線的餅狀圖效果”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。