參考
[1]https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CGContext/Reference/reference.html
[2]https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Applying_styles_and_colors?redirectlocale=en-US&redirectslug=Canvas_tutorial%2FApplying_styles_and_colors#A_lineWidth_example
在drawRect中通過以下代碼可以繪製兩條水平的直線,線的寬度都為1個像素, 通過CGContextSetLineWidth(contextRef, 1);方法設定線條寬度為1個像素。
CGContextRef contextRef = UIGraphicsGetCurrentContext();CGContextSetStrokeColorWithColor(contextRef, [UIColor redColor].CGColor);CGContextSetLineWidth(contextRef, 1);CGContextMoveToPoint(contextRef, 10, 20);CGContextAddLineToPoint(contextRef, 180, 20);CGContextStrokePath(contextRef);CGContextMoveToPoint(contextRef, 10, 40.5);CGContextAddLineToPoint(contextRef, 180, 40.5);CGContextStrokePath(contextRef);
顯示效果如下,可以看出底下的這根線比較亮,而上面的線比較模糊,這是為什麼呢?!
在參考1中關於方法CGContextSetLineWidth說明如下:表示如果設定寬度為1個像素的線,那麼繪製線條分別在所繪路徑的兩邊,每邊各一半寬度,即0.5像素。
或者所謂的線寬指的是給定路徑的中心到兩邊的粗細,換句話是在路徑的兩邊各繪製一半。
The default line width is 1 unit. When stroked, the line straddles the path, with half of the total width on either side.
而正在在螢幕上繪製時,是以像素為單位繪製的,並且對於顯示內容不滿一個像素時,為了平滑顯示內容預設使用了消除鋸齒效果。如下面中間圖形所示,對於1個像素寬度藍色的線條,左右個0.5像素,剩下0.5像素使用消除鋸齒,用淡藍色繪製。
為了避免這種情況,有以下兩種方法
1.繪製時考慮線條寬度,設定路徑時使能夠平分寬度到兩邊,比如:在繪製底下那個紅線時,對Y方向位移了0.5像素,CGContextMoveToPoint(contextRef,
10, 40.5);CGContextAddLineToPoint(contextRef, 180, 40.5); 具體如中最後邊所示。
2.不使用消除鋸齒效果, CGContextSetAllowsAntialiasing(contextRef,NO);即可。
使用方法2後,效果如下,可見此時上下兩根直線繪製效果相同