您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 自繪立體餅圖:CLMView 工具類完整解析

編輯:iOS 開發綜合

專案裡需要呈現一張餅圖,與其每次重寫,不如把它沉澱成一個可重複使用的工具類。下面這份 CLMView 直接繼承 UIView,靠 Core Graphics 手繪扇形、側面厚度與整體漸層,最後再補上圖例,成品帶有一點浮雕般的立體感。

一、頭文件:把資料入口開放出來

這個視圖對外只暴露三組陣列——文字、數值、顏色,另外兩個參數用來控制立體的視覺效果:spaceHeight 決定側面厚度,scaleY 決定整體在垂直方向的壓扁比例。數值越小,看起來就越像俯視角度。

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface CLMView : UIView
{
    float spaceHeight;   // 側面厚度(高度)
    float scaleY;        // 垂直縮放比例
    NSArray *titleArr;   // 圖例文字
    NSArray *valueArr;   // 各扇形的值
    NSArray *colorArr;   // 各扇形的顏色
}

@property(nonatomic, assign) float spaceHeight;
@property(nonatomic, assign) float scaleY;
@property(nonatomic, retain) NSArray *titleArr;
@property(nonatomic, retain) NSArray *valueArr;
@property(nonatomic, retain) NSArray *colorArr;

@end

二、實現文件:drawRect 就是全部的核心

所有繪圖邏輯都集中在 drawRect: 裡。這裡有兩個實作細節值得留意:一是把 currentangel(原文拼字如此)當成「已走過的比例」累加器,用「目前比例 ÷ 總和」換算成弧度;二是只有落在下半圈的扇形才需要畫側面厚度,判斷依據是結束角度是否小於 π。

#import "CLMView.h"

#define K_PI 3.1415
#define KDGREED(x) ((x) * K_PI * 2)

@implementation CLMView
@synthesize spaceHeight, scaleY;
@synthesize titleArr, valueArr, colorArr;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:240.0f/255.0f green:1 blue:1 alpha:1.0];
        spaceHeight = 40;
        scaleY = 0.4;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    // 開啟抗鋸齒,讓圓弧邊緣更平滑
    CGContextSetAllowsAntialiasing(context, TRUE);

    float sum = 0;
    for (int j = 0; j < [valueArr count]; j++) {
        sum += [[valueArr objectAtIndex:j] floatValue];
    }

    CGContextMoveToPoint(context, 160, 230);
    float currentangel = 0;

    // ===== 繪製頂面扇形 =====
    CGContextSaveGState(context);
    CGContextScaleCTM(context, 1.0, scaleY);

    currentangel = 0;
    for (int i = 0; i < [valueArr count]; i++) {

        float startAngle = KDGREED(currentangel);
        currentangel += [[valueArr objectAtIndex:i] floatValue] / sum;
        float endAngle = KDGREED(currentangel);

        CGContextMoveToPoint(context, 160, 230);
        [[colorArr objectAtIndex:i % [valueArr count]] setFill];
        [[UIColor colorWithWhite:1.0 alpha:0.8] setStroke];

        CGContextAddArc(context, 160, 230, 150, startAngle, endAngle, 0);
        CGContextClosePath(context);
        CGContextDrawPath(context, kCGPathFill);

        // ===== 繪製側面(厚度)=====
        float starx = cos(startAngle) * 150 + 160;
        float stary = sin(startAngle) * 150 + 230;
        float endx  = cos(endAngle)   * 150 + 160;
        float endy  = sin(endAngle)   * 150 + 230;
        float endy1 = endy + spaceHeight;

        if (endAngle < K_PI) {
            // 整個扇形都在下半圈,直接畫厚度
            CGMutablePathRef path = CGPathCreateMutable();
            CGPathMoveToPoint(path, nil, starx, stary);
            CGPathAddArc(path, nil, 160, 230, 150, startAngle, endAngle, 0);
            CGPathAddLineToPoint(path, nil, endx, endy1);
            CGPathAddArc(path, nil, 160, 230 + spaceHeight, 150, endAngle, startAngle, 1);
            CGContextAddPath(context, path);

            [[colorArr objectAtIndex:i % [valueArr count]] setFill];
            [[UIColor colorWithWhite:0.9 alpha:1.0] setStroke];
            CGContextDrawPath(context, kCGPathFill);

            [[UIColor colorWithWhite:0.1 alpha:0.4] setFill];
            CGContextAddPath(context, path);
            CGContextDrawPath(context, kCGPathFill);
        }
        else if (startAngle < K_PI) {
            // 跨越下半圈,只畫到 π 為止
            endAngle = K_PI;
            endx = 10;
            endy1 = 230 + spaceHeight;

            CGMutablePathRef path = CGPathCreateMutable();
            CGPathMoveToPoint(path, nil, starx, stary);
            CGPathAddArc(path, nil, 160, 230, 150, startAngle, endAngle, 0);
            CGPathAddLineToPoint(path, nil, endx, endy1);
            CGPathAddArc(path, nil, 160, 230 + spaceHeight, 150, endAngle, startAngle, 1);
            CGContextAddPath(context, path);

            [[colorArr objectAtIndex:i % [valueArr count]] setFill];
            [[UIColor colorWithWhite:0.9 alpha:1.0] setStroke];
            CGContextDrawPath(context, kCGPathFill);

            [[UIColor colorWithWhite:0.1 alpha:0.4] setFill];
            CGContextAddPath(context, path);
            CGContextDrawPath(context, kCGPathFill);
        }
    }

    // ===== 整體漸層 =====
    CGFloat componets[] = {0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.1};
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorspace, componets, nil, 2);
    CGContextDrawRadialGradient(context, gradient,
                                CGPointMake(160, 230), 0,
                                CGPointMake(160, 230), 150, 0);
    CFRelease(colorspace);
    CGGradientRelease(gradient);

    CGContextRestoreGState(context);

    // ===== 繪製圖例 =====
    for (int i = 0; i < [valueArr count]; i++) {
        float origionx = 50;
        float origiony = i * 30 + 200;

        [[colorArr objectAtIndex:i % [valueArr count]] setFill];
        CGContextFillRect(context, CGRectMake(origionx, origiony, 20, 20));
        CGContextDrawPath(context, kCGPathFill);

        if (i < [titleArr count]) {
            NSString *title = [titleArr objectAtIndex:i];
            [title drawAtPoint:CGPointMake(origionx + 50, origiony)
                      withFont:[UIFont systemFontOfSize:16]];
        }
    }
}

- (void)dealloc {
    [titleArr release];
    [valueArr release];
    [colorArr release];
    [super dealloc];
}

@end

幾個容易踩到的細節

漸層那一層是畫在 CGContextRestoreGState 之前,因此它同樣受到 scaleY 的座標壓縮,這正是讓漸層和頂面嚴絲合縫的原因;順序若調動,漸層就會跑位。另外 colorArr 取值時用了 i % [valueArr count],代表顏色數量可以少於扇形數量,會自動循環取用。

三、外部呼叫方式

使用時只要準備好三份陣列,建立視圖、賦值、加進畫面即可。下面的範例示範了如何把「金額佔比」換算成百分比文字,再組出標題。

NSMutableArray *title = [[NSMutableArray alloc] init];
NSMutableArray *value = [[NSMutableArray alloc] init];
NSMutableArray *color = [[NSMutableArray alloc] init];

NSArray *Allcolor = [NSArray arrayWithObjects:
    [UIColor yellowColor], [UIColor blueColor], [UIColor redColor],
    [UIColor brownColor],  [UIColor purpleColor], [UIColor orangeColor],
    [UIColor greenColor],  [UIColor grayColor],
    [UIColor colorWithRed:135.0f/255.0f green:206.0f/255.0f blue:235.0f/255.0f alpha:1],
    [UIColor colorWithRed:240.0f/255.0f green:1 blue:1 alpha:1],
    [UIColor colorWithRed:1 green:0 blue:1 alpha:1],
    [UIColor colorWithRed:0 green:199.0f/255.0f blue:140.0f/255.0f alpha:1],
    [UIColor colorWithRed:160.0f/255.0f green:32.0f/255.0f blue:240.0f/255.0f alpha:1],
    [UIColor colorWithRed:124.0f/255.0f green:252.0f/255.0f blue:0 alpha:1],
    nil];

for (int i = 0; i < [self.onetableDatacostchat count]; i++) {
    float bilv = [[self.onetableDatacostchat objectAtIndex:i] floatValue]
                 / [self.zongcost floatValue];
    float lastbilv = bilv * 100;

    [title addObject:[NSString stringWithFormat:@"%@     %f%@",
                      [self.onetableDatawenzichat objectAtIndex:i],
                      lastbilv, @"%"]];
    [value addObject:[NSNumber numberWithInt:lastbilv]];
    [color addObject:[Allcolor objectAtIndex:i]];
}

CLMView *cv = [[CLMView alloc] initWithFrame:CGRectMake(0, 0, 320, 440)];
cv.titleArr = title;
cv.valueArr = value;
cv.colorArr = color;

[self.view addSubview:cv];
[cv release];
[title release];
[value release];
[color release];

值得一提的是,這裡的圓心與半徑(160, 230 / 150)是寫死的,若要換尺寸或換位置,記得同步調整 drawRect: 中所有相關常量,或進一步把它們抽成屬性。

摘自 RiverAM的專欄

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved