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

iOS 繪圖:用 CGContext 畫出虛線邊框

編輯:iOS 開發綜合

要用 Core Graphics 畫虛線,關鍵是 CGContextSetLineDash,它決定虛線的「實—虛」節奏。下面這段程式示範在檢視上畫一個帶虛線邊框的矩形。

// 目前只能畫在 self 這個視圖上(若有其他 subview 疊在上面,可能會遮蓋線條)
// 呼叫方式:[self drawRect:self.frame];

// 覆寫 drawRect:
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);

    CGContextSetLineWidth(context, 1 * kScreenScale);                              // 線寬
    CGContextSetStrokeColorWithColor(context, [UIColor colorWithHex:@"#959595"].CGColor); // 線色

    CGFloat lengths[] = {2 * kScreenScale, 1 * kScreenScale};                      // 實線 2、虛線 1
    CGContextSetLineDash(context, 0, lengths, 2);                                  // 套用虛線樣式

    CGContextMoveToPoint(context, 5 * kScreenScale, 3 * kScreenScale);             // 起點
    CGContextAddLineToPoint(context, 360 * kScreenScale, 3 * kScreenScale);        // 頂邊
    CGContextAddLineToPoint(context, 362 * kScreenScale, 5 * kScreenScale);        // 右上角
    CGContextAddLineToPoint(context, 362 * kScreenScale, 100 * kScreenScale);      // 右邊
    CGContextAddLineToPoint(context, 360 * kScreenScale, 101 * kScreenScale);      // 右下角
    CGContextAddLineToPoint(context, 5 * kScreenScale, 101 * kScreenScale);        // 底邊
    CGContextAddLineToPoint(context, 4 * kScreenScale, 100 * kScreenScale);        // 左下角
    CGContextAddLineToPoint(context, 4 * kScreenScale, 5 * kScreenScale);          // 左邊
    CGContextAddLineToPoint(context, 5 * kScreenScale, 3 * kScreenScale);          // 回到起點,閉合

    CGContextStrokePath(context);   // 收尾描邊
    CGContextClosePath(context);    // 結束路徑
}

幾個實務上的提醒:

  • 所有座標都乘上 kScreenScale,是為了在 Retina 螢幕上讓線寬保持視覺一致;若你使用 Auto Layout 或直接在 drawRect: 內依 rect 計算,其實可以省略這層換算。
  • lengths 陣列的意義是「畫多長、空多長」交替,改這兩個數字就能調虛線疏密。
  • 更省事的做法是設 layer.lineDashPattern 搭配 CAShapeLayer + path,樣式調整不必重寫 drawRect:。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved