UIView drawRect画线宽度错误

alm*_*now 5 iphone uikit uiview drawrect ios

我试图在我的UIView底部添加一点红线.

我希望这条线是1px线.

有人可以告诉我为什么以下代码:

- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
CGContextSetRGBFillColor(currentContext, 0.0f, 0.0f, 0.0f, 1.0f);
CGContextFillRect(currentContext, RECT(0, 0, rect.size.width, rect.size.height - 8));
CGContextSetLineWidth(currentContext, 1);
CGContextSetRGBStrokeColor(currentContext, 1.0f, 0.0f, 0.0f, 1.0f);
CGContextBeginPath(currentContext);
CGContextMoveToPoint(currentContext, 0, rect.size.height - 7);
CGContextAddLineToPoint(currentContext, rect.size.width, rect.size.height - 7);
CGContextStrokePath(currentContext);
CGContextRestoreGState(currentContext);
}
Run Code Online (Sandbox Code Playgroud)

绘制一条横跨2px高度的线?

Dav*_* M. 14

积分坐标表示像素之间的中间位置; 也就是说,(0,0)位于左上角,左上角和左上角的左上角 ; 类似地,(1,0)第一和第二像素之间; 最后,(0.5,0.5)位于左上角像素的中心.

根据CGContextSetLineWidth的文档,"当描边时,线条横跨路径,两边的总宽度的一半." 因此,如果路径恰好位于像素之间,则该行将在一行像素上被描边一半而在另一行上被描边.

因此,要获得清晰的像素线,必须将坐标偏移半个像素:对于您的x坐标,请使用rect.size.height - 7.5而不是- 7.

顺便说一下,当绘制矩形时,使用它CGRectInset(rect, 0.5, 0.5)来实现这一点很方便.