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

Objective c 在iOS中绘制1像素宽的路径,objective-c,ios,ios5,core-graphics,Objective C,Ios,Ios5,Core Graphics,我正在UIView上的drawRect实现中绘制路径,路径为: CGContextSetLineWidth(context, 0.5); CGContextStrokePath(context); 在CGContext上启用了抗锯齿功能后,我似乎无法绘制1像素的线条 我尝试使用以下选项关闭抗锯齿: CGContextSetShouldAntialias(context, NO); 但是我的角落看起来很糟糕: 如何保持抗锯齿,但停止1像素线的亚像素模糊?在iOS中绘制线时,指定无限窄线的坐

我正在UIView上的drawRect实现中绘制路径,路径为:

CGContextSetLineWidth(context, 0.5);
CGContextStrokePath(context);
在CGContext上启用了抗锯齿功能后,我似乎无法绘制1像素的线条

我尝试使用以下选项关闭抗锯齿:

CGContextSetShouldAntialias(context, NO);
但是我的角落看起来很糟糕:


如何保持抗锯齿,但停止1像素线的亚像素模糊?

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

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


为了解决这个问题,使用一个像素的中间坐标(例如200.5/170.5),并打开反走样。

< P>可以通过:< /P>翻译所有上下文。
- (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);
}
CGContextSaveGState(context);
CGFloat translation = 0.5f / [[UIScreen mainScreen] scale];
CGContextTranslateCTM(context, translation, translation);
... your drawing here ...
CGContextRestoreGState(context);

就这些

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

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)
}

我想我以前试过这个,它成功了,但由于某种原因,它现在不起作用了,我不明白为什么…呸!对不起,我不是真的在想-视网膜显示显然意味着在你绘制的缩放空间中,像素的中间是.25,而不是.50。@chrism+1对我来说不是“duh”,如果我没有像这样偶然发现它,我想我永远也不会发现它……核心图形不使用像素而是点。那是什么?
WKCommonUtil
thingy?@AndréFratelli可能是检测视网膜设备的第三个框架。@AndréFratelli,这是我自己为测试设备是否是视网膜而制作的一个util类。