iphone - 这里如何获取和修改一个像素值?

标签 iphone objective-c ios core-graphics image-manipulation

Listing 2 of Apple's Q & A显示了如何修改 CGImageRef 中的像素的示例。问题是:他们没有展示如何获取像素并修改它的 R G B 和 A 值。

有趣的部分在这里:

 void *data = CGBitmapContextGetData (cgctx);
    if (data != NULL)
    {

        // **** You have a pointer to the image data ****

        // **** Do stuff with the data here ****

    }

现在,假设我想从 x = 100、y = 50 的像素读取红色、绿色、蓝色和 Alpha。我如何访问该像素以及它的 R、G、B 和 A 分量?

最佳答案

首先,您需要知道位图的 bytesPerRow,以及位图中像素的数据类型和颜色格式。 bytesPerRow 可能与 width_in_pixels*bytesPerPixel 不同,因为每行的末尾可能有填充。像素可以是 16 位或 32 位,或者可能是其他大小。像素的格式可以是 ARGB 或 BRGA,或其他一些格式。

对于 32 位 ARGB 数据:

unsigned char *p = (unsigned char *)bytes;
long int i = bytesPerRow * y + 4 * x;  // for 32-bit pixels
alpha = p[i  ];    // for ARGB 
red   = p[i+1];
green = p[i+2];
blue  = p[i+3];

请注意,根据您的 View 变换,Y 轴也可能看起来是颠倒的,这取决于您的期望。

关于iphone - 这里如何获取和修改一个像素值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6388981/

相关文章:

ios - 我应该如何重置我的 Root View Controller 以注销

iOS - 自定义表格单元格不是 UITableView 的全宽

iphone - 我应该为我的 View Controller 使用单例吗?

javascript - iPhone 从 Javascript 调用 Objective-C

objective-c - 如何在 ARC 中使用 CFMutableDictionaryRef

ios - Swift 错误 - 使用未声明的类型 'cell' - Collection View

iOS 模拟器在 macOS Monterey 上崩溃

ios - 如何访问 MKMapItem 的类别或类型

iphone - NStimer——我在这里做错了什么?

ios - Swift 模仿动画 : animation