Quartz 2D - 绘线

参考

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



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值