在iOS中绘制1个像素宽的路径

时间:2012-05-27 11:03:03

标签: objective-c ios ios5 core-graphics

我在UIView上的drawRect实现中绘制了一条路径:

CGContextSetLineWidth(context, 0.5);
CGContextStrokePath(context);

在我的CGContext上使用抗锯齿,我似乎无法绘制1 px行。

on

我尝试用以下方式关闭抗锯齿:

CGContextSetShouldAntialias(context, NO);

然后我的角落看起来很可怕:

off

如何保持抗锯齿效果但是停止1像素线的子像素模糊?

4 个答案:

答案 0 :(得分:23)

在iOS中绘制线条时,指定无限窄线条的坐标。然后,绘制的线将延伸到该线的两侧,行程宽度的一半。

如果您的无限窄线具有整数坐标并且是水平或垂直的,则绘制的线将是两个像素宽和灰色而不是一个像素宽和黑色(具有抗锯齿)。如果没有抗锯齿,线条会略微移动,但角落看起来很难看。

要解决此问题,请使用像素中间的坐标(例如200.5 / 170.5)并打开消除锯齿功能。

答案 1 :(得分:10)

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    CGFloat inset = 0.5 / [[UIScreen mainScreen] scale];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    // draw
    CGContextSetLineWidth(context, inset);
    CGContextSetStrokeColorWithColor(context, _lineColor.CGColor);
    CGContextMoveToPoint(context, inset, 0);
    CGContextAddLineToPoint(context, inset, CGRectGetHeight(rect));
    CGContextStrokePath(context);
    CGContextRestoreGState(context);
}

答案 2 :(得分:0)

您可以通过以下方式翻译所有上下文:

CGContextSaveGState(context);
CGFloat translation = 0.5f / [[UIScreen mainScreen] scale];
CGContextTranslateCTM(context, translation, translation);
... your drawing here ...
CGContextRestoreGState(context);

这就是全部!

答案 3 :(得分:0)

对我有用的唯一解决方案是:

override func drawRect(rect: CGRect) {

    let context = UIGraphicsGetCurrentContext()

    CGContextSetLineWidth(context, 0.5)

    CGContextMoveToPoint(context, 0.0, 0.25)
    CGContextAddLineToPoint(context, rect.size.width, 0.25)

    CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
    CGContextStrokePath(context)
}