需求是畫一條分隔用的虛線。最偷工的作法是拿一張虛線小圖水平重複貼上,但換解析度就要重切圖,顏色也不好改。與其如此,不如封裝一個 UIView 子類,用 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) {
_lineColor = [UIColor redColor];
_startPoint = CGPointMake(0, 1);
_endPoint = CGPointMake(CGRectGetWidth(self.bounds), 1);
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctx);
CGContextSetLineWidth(ctx, 0.5);
CGContextSetStrokeColorWithColor(ctx, self.lineColor.CGColor);
// 畫 4 個單位、空 2 個單位,循環往復
CGFloat lengths[] = {4, 2};
CGContextSetLineDash(ctx, 0, lengths, 2);
CGContextMoveToPoint(ctx, self.startPoint.x, self.startPoint.y);
CGContextAddLineToPoint(ctx, self.endPoint.x, self.endPoint.y);
CGContextStrokePath(ctx);
CGContextClosePath(ctx);
}
@end
CGContextSetLineDash(context, phase, lengths, count) 的四個參數分別是:上下文、起始偏移相位、長度陣列,以及陣列元素個數。第三個參數常有人誤傳陣列長度以外的數字,導致虛線間距不如預期。
想畫垂直虛線,只要把起點與終點的 x 座標設為相同、y 座標分別為頂端與底端即可;斜線同理,改兩點座標就行,這個封裝不必動到繪圖邏輯。
另外別忘了,若在 initWithFrame: 中讀取 self.bounds,此時 frame 已由呼叫方決定,是安全的;但若在 init 中讀取,bounds 還是 0,寬度會算錯。
DashesLineView *line = [[DashesLineView alloc]
initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 2)];
line.lineColor = [UIColor lightGrayColor];
[self.view addSubview:line];
改成用 layer 的 anchorPoint 或搭配 Auto Layout 時,記得在 layoutSubviews 中重新設定端點座標並呼叫 setNeedsDisplay,否則旋轉或尺寸變更後虛線不會跟著重畫。