为什么这不能正确划线?

时间:2013-05-14 15:20:42

标签: ios core-graphics

CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextSetStrokeColorWithColor(currentContext, hh2DarkGray.CGColor);
CGFloat lengths[] = {0, 8};
CGContextSetLineCap(currentContext, kCGLineCapRound);
CGContextSetLineWidth(currentContext, 1);
CGContextSetLineDash(currentContext, 0.0f, lengths, 2);

CGContextBeginPath(currentContext);
CGContextMoveToPoint(currentContext, x1, y1);
CGContextAddLineToPoint(currentContext, x2, y2);

CGContextClosePath(currentContext);
CGContextDrawPath(currentContext, kCGPathStroke);

在上面的代码中我做错了什么使得点不均匀分布?它看起来像这样。

。 .. .. .. .. .. .. .. .. .. .. 当我需要它看起来像这样 。 。 。 。 。 。 。 。 。 。 。 。 。 。

我完全迷失了,我能找到的所有其他帖子都没有指出这类问题。请帮帮忙?

2 个答案:

答案 0 :(得分:4)

问题是你正在关闭路径 - 这隐含地将一条线画回第一点。如果您的路径仅由两点之间的直线组成,则基本上会直接在彼此的顶部绘制两条直线,这会导致出现其他点(这些是第二行,在虚线图案中有一个偏移)。

解决方案:只需移除对CGContextClosePath的调用。

使用{1, 8}代替{0, 8}作为短划线模式也更合乎逻辑,因为您需要绘制一个点,但在实践中,它似乎没有什么区别

答案 1 :(得分:0)

尝试将0.5添加到您的线坐标:

CGContextMoveToPoint(currentContext, x1 + 0.5, y1 + 0.5);
CGContextAddLineToPoint(currentContext, x2 + 0.5, y2 + 0.5);

您必须考虑逻辑坐标而不是像素索引。当你想绘制像素完美线条时,你必须传递一些像素中心的坐标。否则你会得到四舍五入的文物。

相关问题