ios - 为 UIBezierPath 禁用抗锯齿

标签 ios core-graphics

我需要在没有抗锯齿的情况下渲染 UIBezierPaths,然后将它们保存为 PNG 以保留完整的像素表示(例如,不要让 JPEG 弄乱图像)。我试过在抚摸 UIBezierPaths 之前调用下面的 CG 函数,但似乎对生成的渲染图像没有任何影响。路径仍然使用抗锯齿渲染(即平滑)。

CGContextSetShouldAntialias(c, NO);
CGContextSetAllowsAntialiasing(c, NO);
CGContextSetInterpolationQuality(c, kCGInterpolationNone);

如有任何点击,我们将不胜感激。

最佳答案

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

enter image description here

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

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

    [[UIColor redColor] setStroke];
    UIBezierPath *path = [self myPath];
    [path stroke];
}

并捕获屏幕,来自 How to take a screenshot programmatically

- (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];
}

如果您使用的是 CAShapeLayer,那么我认为您无法控制屏幕上的抗锯齿,因为 as the documentation says :

The shape will be drawn antialiased, and whenever possible it will be mapped into screen space before being rasterized to preserve resolution independence. However, certain kinds of image processing operations, such as CoreImage filters, applied to the layer or its ancestors may force rasterization in a local coordinate space.

但是,不管屏幕上的抗锯齿如何,如果你想让你的屏幕快照不被抗锯齿,你可以将你的 CGContextSetShouldAntialias 插入到 captureScreen 例程中:

- (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];
}

关于ios - 为 UIBezierPath 禁用抗锯齿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15417410/

相关文章:

ios - 为什么AnnotationView didChangeDragState 调用了很多次?

ios - 将swift程序分成多个文件

ios - 将字符串中单词的每个首字母大写

iphone - 在 iOS 6 和 iOS 7 中更改不同的 UIImage 颜色

ios - 在iOS和OSX之间共享CGColor

objective-c - UIView 在所有不随屏幕旋转的东西前面?

ios - 如何使用 Swift 从 Metal 纹理中读取半精度 float ?

macos - 在 OS X 上启动新的后台 GUI 登录 session 或登录窗口,CGSCreateLoginSessionWithDataAndVisibility 函数

ios - 滚动时扭曲 UITableViewCell?

ios - 无法将特定的CGColor应用于CGContextSetFillColor