我在 UIView 上的 drawRect 实现中绘制了一条路径:
CGContextSetLineWidth(context, 0.5);
CGContextStrokePath(context);
在我的 CGContext 上启用抗锯齿,我似乎无法绘制 1 px 的线。

我尝试使用以下方法关闭抗锯齿:
CGContextSetShouldAntialias(context, NO);
但后来我的角落看起来很糟糕:

如何保持抗锯齿打开但停止 1 像素线的这种子像素模糊?
我在 UIView 上的 drawRect 实现中绘制了一条路径:
CGContextSetLineWidth(context, 0.5);
CGContextStrokePath(context);
在我的 CGContext 上启用抗锯齿,我似乎无法绘制 1 px 的线。

我尝试使用以下方法关闭抗锯齿:
CGContextSetShouldAntialias(context, NO);
但后来我的角落看起来很糟糕:

如何保持抗锯齿打开但停止 1 像素线的这种子像素模糊?
当您在 iOS 中绘制一条线时,您指定了一条无限窄线的坐标。然后,绘制的线将延伸到该线的两侧,宽度为笔划宽度的一半。
如果您的无限窄线具有整数坐标并且是水平或垂直的,则绘制的线将是两个像素宽和灰色,而不是一个像素宽和黑色(具有抗锯齿)。如果没有抗锯齿,线条会稍微移动,但边角看起来很难看。
要解决此问题,请使用像素中间的坐标(例如 200.5 / 170.5)并打开抗锯齿。
- (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)
}