我想在我的 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);
}
绘制一条高度为 2px 的线?
最佳答案
积分坐标表示像素之间的中间位置;也就是说,(0,0) 在左上角,在左上角像素的左上方;同样,(1,0) 在第一个和第二个像素之间;最后,(0.5,0.5) 位于左上角像素的中心。
根据 the documentation for CGContextSetLineWidth , “当被抚摸时,这条线横跨路径,两边的总宽度的一半。”因此,如果路径恰好位于像素之间,则线条将在一行像素上描边,一半在另一行像素上描边。
因此,要获得清晰的像素线,您必须将您的坐标偏移半个像素:对于您的 x
坐标,请改用 rect.size.height - 7.5
- 7
。
顺便说一下,在绘制矩形时,使用CGRectInset(rect, 0.5, 0.5)
可以很方便地实现这一点。
关于iphone - UIView drawRect 绘图线宽度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3661076/