自定义视图中的奇怪反锯齿
问题描述:
我有一个自定义UIView
,它使用其-[drawRect:]
方法绘制。自定义视图中的奇怪反锯齿
问题在于抗锯齿行为非常奇怪,因为黑线水平线或垂直线非常模糊。
如果我禁用了与CGContextSetAllowsAntialiasing
的抗锯齿,则所有内容都按预期绘制。
抗锯齿:
alt text http://dustlab.com/stuff/antialias.png
无抗锯齿(这看起来像AA预期的结果):
alt text http://dustlab.com/stuff/no_antialias.png
线宽正好是1,和所有的坐标是整数值。
如果我使用CGContextStrokeRect
绘制一个矩形,但是如果我绘制完全相同的CGRect
和UIRectStroke
,则会发生同样的情况。
答
由于行程膨胀等量至两侧,一条线的一个像素宽度的不得将放置在整数坐标上,但以0.5像素偏移量放置。
计算描边线这样的正确的坐标:
CGPoint pos = CGPointMake(floorf(pos.x) + 0.5f, floorf(pos.y) + 0.5f);
BTW:不要投你的价值观为int和背部浮摆脱小数部分。 C中有一个函数floor
。
答
在您的视图框架中,您可能具有不是整数的浮点值。虽然帧足够精确做一个像素(浮点)的级分,将得到的模糊,除非你转换为int
CGRect frame = CGRectMake((int)self.frame.bounds..., (int)...., (int)...., (int)....);
除此之外,Apple在Cocoa绘图指南的“执行像素精确绘图”部分中提供了一些不错的提示和示例代码:http://developer.apple.com/mac/library/documentation/Cocoa/ Conceptual/CocoaDrawingGuide/Transforms/Transforms.html#// apple_ref/doc/uid/TP40003290-CH204-BCICIJAJ – 2009-09-21 16:32:45
这里是避免没有任何代码的简单方法http://www.techpaa.com/2012/06/avoiding -view-edge-antialiasing.html – ShivaPrasad 2012-06-18 08:31:01
@jeeva'UIViewEdgeAntialiasing'仅适用于图层的边缘。问题是关于在Quartz中绘制的线条。 'UIViewEdgeAuthoriasing'不会影响Quartz绘图。 – 2012-06-20 07:15:24