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

iOS 繪製虛線的三種做法:drawRect、CAShapeLayer 與貼圖

編輯:iOS 開發綜合

虛線在 UI 上很常見——分隔線、裁切提示、上傳框邊界都會用到。iOS 沒有現成的「虛線 view」,但提供了幾條路可走,各有適用場景。

方法一:覆寫 drawRect:

直接用 Core Graphics 手繪,最直觀,也最容易做客製路徑(曲線、折線、任意形狀)。

 - (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(currentContext, [UIColor blackColor].CGColor); // 虛線顏色
    CGContextSetLineWidth(currentContext, 1);                                     // 線寬

    CGContextMoveToPoint(currentContext, 0, 0);                                   // 起點
    CGContextAddLineToPoint(currentContext, self.frame.origin.x + self.frame.size.width, 0); // 終點

    // 排列規則:先畫 3 個單位再留 1 個單位空白
    CGFloat arr[] = {3, 1};
    CGContextSetLineDash(currentContext, 0, arr, 2);   // 最後一個參數是 arr 的成員數量

    CGContextDrawPath(currentContext, kCGPathStroke);
}

CGContextSetLineDash 的 phase 參數(這裡是 0)代表「從線的哪個相位開始」,若想做出螞蟻線(marching ants)效果,只要讓這個值隨時間遞增並反覆呼叫 setNeedsDisplay 即可。

這個做法的缺點是:一旦尺寸或顏色改變就得重繪,而且 drawRect 本身有一定成本,不適合大量使用。

方法二:使用 CAShapeLayer

把虛線畫在獨立的 layer 上,改動屬性時由 Core Animation 接手,效能與彈性都更好,也不會觸發父 view 的重繪。

 CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:self.bounds];
[shapeLayer setPosition:CGPointMake(self.frame.size.width / 2.0, self.frame.size.height)];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];   // 不填色
[shapeLayer setStrokeColor:[UIColor blackColor].CGColor]; // 虛線顏色
[shapeLayer setLineWidth:self.frame.size.height];         // 線寬
[shapeLayer setLineJoin:kCALineJoinRound];
// 線寬與間距
[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:3],
                                                         [NSNumber numberWithInt:1], nil]];

// 建立路徑
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, self.frame.size.width, 0);
[shapeLayer setPath:path];
CGPathRelease(path);

[self.layer addSublayer:shapeLayer];

注意 fillColor 要設為 clearColor,否則路徑圍起來的區域會被填滿。另外 CGPathCreateMutable 配置出來的 path 記得 CGPathRelease,若在 drawRect 這類高頻方法中忘記釋放,很快就是記憶體洩漏。

有人已經把這套邏輯包成好用的類方法,值得參考:

 /**
  * lineView    : 要畫成虛線的 view
  * lineLength  : 虛線寬度
  * lineSpacing : 虛線間距
  * lineColor   : 虛線顏色
  */
+ (void)drawDashLine:(UIView *)lineView
          lineLength:(int)lineLength
         lineSpacing:(int)lineSpacing
           lineColor:(UIColor *)lineColor {
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    // ... 其餘設定同上 ...
    [shapeLayer setStrokeColor:lineColor.CGColor];
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength],
                                                             [NSNumber numberWithInt:lineSpacing], nil]];
    // ... 路徑設定 ...
    [lineView.layer addSublayer:shapeLayer];
}

(此段為部分程式碼,完整版本可自行搜尋。)

方法三:用一張貼圖(最省事的偷吃步)

如果虛線的樣式固定、不需要動態調整,直接請設計師切一張 1px 高的虛線圖,用 colorWithPatternImage: 平鋪即可。

 UIImageView *imgDashLineView = [[UIImageView alloc]
    initWithFrame:CGRectMake(15, 200, self.view.frame.size.width - 30, 1)];
[imgDashLineView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"xuxian.png"]]];
[self.view addSubview:imgDashLineView];

這種做法的優點是程式碼最少、效能最好;缺點是顏色寫死在圖片裡,換色就得換圖,而且非整數倍寬度時平鋪可能出現接縫。

該選哪一個?

動態、需要換色或改間距、數量不多——選 CAShapeLayer,這是多數情況下的最佳解。

路徑不規則(例如圓形虛線框、自訂曲線),或需要螢幕上的螞蟻線動效——選 drawRect,因為它能完全掌控繪製流程。

樣式固定、效能極端敏感(例如長列表的 cell 分隔線)——選 貼圖,反覆解碼的消耗遠低於建立 layer。

以上內容部分整理自網路資源,若有涉及侵權請告知。歡迎一起討論,有問題可留言。

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