Quartz 2D – 繪線

來源:互聯網
上載者:User

參考

[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後,效果如下,可見此時上下兩根直線繪製效果相同



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.