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

chr*_*ism 12 core-graphics objective-c ios ios5

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

CGContextSetLineWidth(context, 0.5);
CGContextStrokePath(context);
Run Code Online (Sandbox Code Playgroud)

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

上

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

CGContextSetShouldAntialias(context, NO);
Run Code Online (Sandbox Code Playgroud)

但后来我的角落看起来很糟糕:

离

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

Cod*_*odo 23

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

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

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

  • 咄!抱歉,我并没有真正想到 - Retina显然显然意味着像素的中间是.25,而不是.50在您绘制的缩放空间中. (7认同)

Che*_*ong 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);
}
Run Code Online (Sandbox Code Playgroud)