我正在尝试识别一些像素颜色,但我认为我不清楚人们在做什么。 我在这里和谷歌上看到了很多示例代码,但我认为我遗漏了一些东西。
这是我调用该方法的方式:
app.h
UIImage *image;
app.m
- (id)init {
self = [super init];
if(self) {
...
image = [UIImage imageNamed:@"bwimage.bmp"];
...
[self checkRailBW:image :x_pos :y_pos]
...
方法如下:
-(BOOL)checkRailBW: (UIImage*)background : (CGFloat)x : (CGFloat)y{
CGImageRef image = background.CGImage;
NSUInteger width = CGImageGetWidth(background);
NSUInteger height = CGImageGetHeight(background);
// Setup 1x1 pixel context to draw into
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char rawData[4];
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData,
1,
1,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
// Draw the image
CGContextDrawImage(context,
CGRectMake(x, y-height, width, height),
image);
// Done
CGContextRelease(context);
// Get the pixel information
unsigned char red = rawData[0];
unsigned char green = rawData[1];
unsigned char blue = rawData[2];
unsigned char alpha = rawData[3];
}
我永远无法获得有关红色、绿色或蓝色的任何数据。
顺便说一句...我正在追踪黑色像素。我正在处理黑白图像,因此它具有 1 位/像素。
谢谢你的帮助!
最佳答案
您始终将图像的左上角像素绘制到 1x1 上下文中。您需要更改要在正确位置绘制所需像素的 CGRect
的原点,或者设置当前变换矩阵以偏移绘制发生的位置,以便有问题的像素落在你的上下文的起源上。
但是您可能不应该执行其中任何一项,因为这是获得您想要的内容的一种极其低效的方法。你到底想在这里做什么?您显然想要图像中某个像素的颜色,但目的是什么?您是否遍历图像中的所有像素?如果是这样,您可能应该将图像绘制到位图中一次,然后使用指针算法获取要测试的像素。
或者,如果您尝试以某种方式修改像素,则应使用其他工具,例如 CoreImage 或 OpenGL。
关于ios - 处理像素时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20926534/