参考
在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后,效果如下,可见此时上下两根直线绘制效果相同

1709

被折叠的 条评论
为什么被折叠?



