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

iOS 繪製曲線走勢圖:UIBezierPath 串接 CAShapeLayer 實作

編輯:iOS 開發綜合

要在 iOS 上畫一張折線/曲線走勢圖,最經典的組合是 UIBezierPath 描述路徑 + CAShapeLayer 負責渲染。這個搭配的好處是:路徑物件與顯示層分離,後續要做動畫、換顏色、改線寬都非常容易。

完整實作

- (void)drawLine
{
    // 走勢圖的背景 view
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 300)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];

    // ── 第一、用 UIBezierPath 描述線段 ──

    UIBezierPath *path = [UIBezierPath bezierPath];

    // 四個資料點
    CGPoint point  = CGPointMake(10,  10);
    CGPoint point1 = CGPointMake(200, 100);
    CGPoint point2 = CGPointMake(240, 200);
    CGPoint point3 = CGPointMake(290, 200);

    NSArray *arr = @[ [NSValue valueWithCGPoint:point],
                      [NSValue valueWithCGPoint:point1],
                      [NSValue valueWithCGPoint:point2],
                      [NSValue valueWithCGPoint:point3] ];

    NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, arr.count)];

    // ── 第二、逐點串接並標記節點 ──

    [arr enumerateObjectsAtIndexes:set options:0 usingBlock:^(NSValue *pointValue, NSUInteger idx, BOOL *stop) {

        CGPoint pt = [pointValue CGPointValue];
        [path addLineToPoint:pt];

        // (一)以矩形畫出方形節點
        CGRect rect;
        rect.origin.x    = pt.x - 1.5;
        rect.origin.y    = pt.y - 1.5;
        rect.size.width  = 4;
        rect.size.height = 4;

        // (二)若想畫圓形節點,改用:
        // CGRect rect = CGRectMake(pt.x - 2, pt.y - 2, 4, 4);

        UIBezierPath *arc = [UIBezierPath bezierPathWithOvalInRect:rect];
        [path appendPath:arc];
    }];

    // ── 第三、把 path 交給 CAShapeLayer 渲染 ──

    CAShapeLayer *lineLayer = [CAShapeLayer layer];
    lineLayer.frame        = CGRectMake(0, 150, 320, 400);
    lineLayer.fillColor    = [UIColor redColor].CGColor;
    lineLayer.path         = path.CGPath;      // 注意是 CGPath,不是 Path
    lineLayer.strokeColor  = [UIColor redColor].CGColor;

    [view.layer addSublayer:lineLayer];

    // ── 附加效果:像幕布一樣拉開的進場動畫 ──

    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 400)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];

    [UIView animateWithDuration:5 animations:^{
        view1.frame = CGRectMake(320, 100, 320, 400);   // 向右滑出
    }];
}

程式碼中的幾個關鍵細節

1. 為什麼要用 NSValue 包裝 CGPoint

CGPoint 是 C 結構體,不能直接放進 NSArray。必須用 [NSValue valueWithCGPoint:] 包裝成物件,取出時再用 -CGPointValue 還原。這是所有「把 CG 結構放進集合類別」場景的通用解法。

2. 起始點的處理

範例直接從第一個點開始 addLineToPoint:。嚴格來說,若 path 是空的,應該先用 moveToPoint: 設定起點,再對第二點之後呼叫 addLineToPoint:。否則部分情況下會從 (0, 0) 拉一條意想不到的線到第一個點。實務上建議改成:

BOOL isFirst = YES;
[arr enumerateObjectsAtIndexes:set options:0 usingBlock:^(NSValue *pointValue, NSUInteger idx, BOOL *stop) {
    CGPoint pt = [pointValue CGPointValue];
    if (isFirst) {
        [path moveToPoint:pt];
        isFirst = NO;
    } else {
        [path addLineToPoint:pt];
    }
    // ... 畫節點
}];

3. CAShapeLayer 的三個必要屬性

  • path:要繪製的 CGPathRef,注意賦值時要取 path.CGPath
  • strokeColor:線條顏色(CGColor,不是 UIColor)
  • fillColor:內部填色;只要畫線、不要填滿時可設為 [UIColor clearColor].CGColor 或 nil

還可加上 lineWidth(線寬)、lineCap(線端樣式)、lineJoin(轉角樣式)做視覺微調。

進階:畫平滑曲線而非折線

折線在數據劇烈變化時看起來很生硬。若要平滑曲線,可改用:

// 二次貝茲曲線:用相鄰兩點的中点作為端點,原點作為控制點
[path moveToPoint:points[0]];
for (NSUInteger i = 1; i < points.count - 1; i++) {
    CGPoint current = [points[i] CGPointValue];
    CGPoint next    = [points[i + 1] CGPointValue];
    CGPoint mid     = CGPointMake((current.x + next.x) / 2.0,
                                  (current.y + next.y) / 2.0);
    [path addQuadCurveToPoint:mid controlPoint:current];
}
[path addLineToPoint:points.lastObject.CGPointValue];

若需要更精細的控制(例如穿過每一個資料點的 Catmull-Rom 平滑),可用三次貝茲曲線 addCurveToPoint:controlPoint1:controlPoint2: 自行計算控制點。

讓走勢圖「長出來」的動畫

CAShapeLayer 最大的優勢是能做線條生長動畫,這是 UIView 無法做到的:

// 1. 取得路徑總長度
CGFloat length = lineLayer.path.length;   // 需自行以 CGPathGetLength 或近似計算取得

// 2. 設為完全隱藏
lineLayer.strokeStart = 0;
lineLayer.strokeEnd   = 0;

// 3. 動畫展開
[CATransaction begin];
[CATransaction setAnimationDuration:2.0];
lineLayer.strokeEnd = 1.0;
[CATransaction commit];

strokeStart 與 strokeEnd 是 CAShapeLayer 專屬屬性(介於 0~1 之間,代表路徑的百分比位置),做進度環、心電圖掃描、SVG 簽名效果都靠它。

幾個實務建議

  • 座標換算要小心:資料通常要從「數值空間」映射到「視圖空間」,記得處理 Y 軸反轉(數值越大通常畫得越高,但 UIKit 的 Y 軸向下)。
  • 動態資料用 drawRect::若資料會頻繁更新,改在 view 的 drawRect: 中直接畫,並用 setNeedsDisplay 觸發重繪,比反覆重建 layer 更有效率。
  • 大量資料點:點數破千時,CAShapeLayer 的渲染會變重。可考慮先做簡化(如 Ramer–Douglas–Peucker 演算法)或改用 Metal / Core Plot 這類專業繪圖框架。
  • 若要互動:CAShapeLayer 本身不接收事件。要支援點擊某個資料點、顯示 tooltip,需要另外用 CAShapeLayer.hitTest 或自行做座標距離判斷。

if 需要完整的圖表元件(座標軸、格線、縮放、tooltip),可以考慮 Charts(原 iOS-Charts)、Core Plot 或 Swift Charts(iOS 16+)。但若是簡單的走勢線,UIBezierPath + CAShapeLayer 這二十行就足夠,且完全可控。

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