禁用UIBezierPath的抗锯齿功能

alo*_*njr 7 core-graphics ios

我需要渲染没有消除锯齿的UIBezierPaths,然后将它们保存为PNG以保留完整的像素表示(例如,不要让JPEG图像混淆).我在尝试触摸UIBezierPaths之前尝试调用下面的CG函数,但似乎没有对生成的渲染图像产生任何影响.路径仍然使用抗锯齿(即平滑)进行渲染.

CGContextSetShouldAntialias(c, NO);
CGContextSetAllowsAntialiasing(c, NO);
CGContextSetInterpolationQuality(c, kCGInterpolationNone);
Run Code Online (Sandbox Code Playgroud)

任何点击都将非常感激.

Rob*_*Rob 14

当我使用这些选项时,它会关闭抗锯齿功能.左侧是默认选项.在右边,有你的选择.

在此输入图像描述

如果您正在使用UIView子类,这很容易控制.这是我的drawRect:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetShouldAntialias(context, NO);

    [[UIColor redColor] setStroke];
    UIBezierPath *path = [self myPath];
    [path stroke];
}
Run Code Online (Sandbox Code Playgroud)

并捕获屏幕,从如何以编程方式截取屏幕截图

- (void)captureScreen
{
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(self.window.bounds.size);
    [self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data = UIImagePNGRepresentation(image);
    [data writeToFile:[self screenShotFilename] atomically:YES];
}
Run Code Online (Sandbox Code Playgroud)

如果您正在使用a CAShapeLayer,那么我认为您无法在屏幕上控制抗锯齿,因为文档说:

将绘制抗锯齿形状,并且在光栅化之前将尽可能将其映射到屏幕空间以保持分辨率独立性.但是,应用于图层或其祖先的某些类型的图像处理操作(如CoreImage滤镜)可能会强制在局部坐标空间中进行光栅化.

但是,无论屏幕上的抗锯齿如何,如果您想让屏幕快照不被抗锯齿,您可以将其插入CGContextSetShouldAntialiascaptureScreen例程中:

- (void)captureScreen
{
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(self.window.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetShouldAntialias(context, NO);
    [self.window.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData * data = UIImagePNGRepresentation(image);
    [data writeToFile:[self screenShotFilename] atomically:YES];
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*ier 5

你是从哪里来c的?你确定这cUIGraphicsGetCurrentContext()你使用的绘图周期中的相同[UIBezierPath stroke]吗?从上面的例子中很难说清楚.

如果您想确定要绘制到正在配置的相同上下文,请CGPath从中获取UIBezierPath,然后直接绘制它:

- (void)drawRect:(CGRect)rect {
  CGContextRef context = UIGraphicGetCurrentContext();
  CGPathRef path = [self.bezier CGPath];
  CGContextSetShouldAntialias(context, NO);
  CGContextAddPath(context, path);
  CGContextStrokePath(context);
}
Run Code Online (Sandbox Code Playgroud)