iphone - UIView drawRect 绘图线宽度错误

标签 iphone ios uiview uikit drawrect

我想在我的 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/

相关文章:

javascript - 没有 phonegap.js

iphone - 导航 Controller 中的后退按钮动画

android - 在 flutter 中隐藏后退按钮

c++ - CCSpriteFrameCache 无法正确检索后缀为 '-ipad' 的图像

ios - iPhone:从位置管理器或 map 工具包获取国家/地区代码

ios - 如何从委托(delegate)方法 cellForRowAtIndexPath : 内部调用的方法编辑完成 block 中的 UITableViewCell

ios - 我在 `init` 方法和 `viewDidLoad` 方法中设置了什么?

objective-c - 如何应对点击速度过快的用户

objective-c - TableView 顶部的 View 消失

iPhone 网络摄像头馈送