iOS 使用 UIGraphicsGetImageFromCurrentImageContext 检测屏幕上的某些像素

标签 ios objective-c uibezierpath bezier

我有一个 UIView,用户可以在其中绘制各种 UIBezierPaths。

我需要分析绘制的 BezierPaths 来处理某些模式。我还没有找到任何将 UIBezierPaths 转换为坐标/点列表的解决方案,这似乎是不可撤消的?这很奇怪,因为必须存储这些数据并以某种方式使用它来绘制实际路径..

因此,为了绕过这个问题,我决定绘制宽度为 1px 的 BezierPath:

[path setLineWidth:1];

并将我的 UIView 转换为 UIImage:

UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

然后我可以通过获取图像中某个像素位置的颜色来识别像素:

- (UIColor *)colorAtPixel:(CGPoint)point {
    CGImageRef imageRef = [self CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    long bytesPerRow = bytesPerPixel * width;
    int bitsPerComponent = 8;

    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));

    CGContextRef context = CGBitmapContextCreate(rawData,
                                                 width,
                                                 height,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGColorSpaceRelease(colorSpace);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    long byteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel;
    CGFloat red   = (rawData[byteIndex] * 1.0) / 255.0;
    CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0 ;
    CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0 ;
    CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;

    byteIndex += 4;
    UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    free(rawData);

    return color;
}

现在我的问题是生成的图像是模糊的,如果绘制一条直线 1px BezierPath 线并将其转换为 UIImage,则该线的宽度为 3 倍,因为它变得模糊。

我该如何解决这个问题?实际上没有可能的方法将 BezierPaths 转换为坐标列表吗?

最佳答案

这是由于抗锯齿渲染。

See this question on SO for information on how to turn this of.

我相信你最好自己渲染贝塞尔曲线。内存占用非常小,速度会更快。

关于iOS 使用 UIGraphicsGetImageFromCurrentImageContext 检测屏幕上的某些像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30123602/

相关文章:

iOS 7 使用 AVPlayer 在锁定屏幕上倒回歌曲

iphone - 控制 UIScrollView 越界?

iphone - 添加成就机制-如何设计- objective-c

ios - CABasicAnimation CALayer 路径动画方向

ios - 在运行时为弹出 View anchor 创建按钮

ios - 在 iOS 导航 Controller 的代码中自定义图像大小

ios - pointInside :withEvent inside uibezierpath (overlapping area between two views)

ios - 为什么[[bezierPath closePath]`方法无法关闭我的路径?

iphone - 除了自定义 URL 方案之外,还有其他方法可以调用应用内电话吗?

objective-c - 更改 UITextField 键盘的色调