要在 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); // 向右滑出
}];
}
CGPoint 是 C 結構體,不能直接放進 NSArray。必須用 [NSValue valueWithCGPoint:] 包裝成物件,取出時再用 -CGPointValue 還原。這是所有「把 CG 結構放進集合類別」場景的通用解法。
範例直接從第一個點開始 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];
}
// ... 畫節點
}];
CGPathRef,注意賦值時要取 path.CGPathCGColor,不是 UIColor)[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 簽名效果都靠它。
drawRect: 中直接畫,並用 setNeedsDisplay 觸發重繪,比反覆重建 layer 更有效率。CAShapeLayer.hitTest 或自行做座標距離判斷。if 需要完整的圖表元件(座標軸、格線、縮放、tooltip),可以考慮 Charts(原 iOS-Charts)、Core Plot 或 Swift Charts(iOS 16+)。但若是簡單的走勢線,UIBezierPath + CAShapeLayer 這二十行就足夠,且完全可控。