您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

用 drawRect 畫出 iOS 自訂虛線

編輯:iOS 相關資訊

要在 iOS 上畫虛線,最古典也最直接的方式是繼承 UIView 並覆寫 drawRect:,透過 Core Graphics 設定線條虛線樣式。

頭檔宣告

#import <UIKit/UIKit.h>

@interface DashesLineView : UIView
@property (nonatomic) CGPoint startPoint;      // 虛線起點
@property (nonatomic) CGPoint endPoint;        // 虛線終點
@property (nonatomic, strong) UIColor *lineColor;  // 虛線顏色
@end

實作

#import "DashesLineView.h"

@implementation DashesLineView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextBeginPath(context);
    CGContextSetLineWidth(context, 0.5);             // 線寬
    CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);

    CGFloat lengths[] = {4, 2};                      // 先畫 4、再空 2,以此循環
    CGContextSetLineDash(context, 0, lengths, 2);    // count 必須等於陣列長度

    CGContextMoveToPoint(context, self.startPoint.x, self.startPoint.y);
    CGContextAddLineToPoint(context, self.endPoint.x, self.endPoint.y);
    CGContextStrokePath(context);
    CGContextClosePath(context);
}

@end

幾個實務重點

lengths 陣列描述的是「一段實線多長、一段空白多長」的循環節奏,{4, 2} 就是 4 單位實線接 2 單位間隔。CGContextSetLineDash 的最後一個參數是 count,必須與陣列元素個數相符,寫錯會直接讀到記憶體外的資料。

使用上有幾點要注意:起點與終點請用 view 自身的座標系,也就是由外部在設定 frame 之後再指定;如果起終點會變動,別忘了呼叫 setNeedsDisplay 觸發重繪。另外,drawRect: 的每次呼叫都伴隨一次繪圖上下文取得與路徑建構,如果虛線數量很多又需要頻繁更新,改用 CAShapeLayer 搭配 lineDashPattern 會更省資源,而且能直接享受/Core Animation 的動畫。

最後,只要是覆寫了 drawRect: 的 view,就不應該設定 opaque 為 YES 以外的透明背景假設,並且避免在動畫期間反覆呼叫,Apple 的註解裡也提醒過空實作會拖慢效能。

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