我有这个代码,它主要使用C代码检查像素颜色:
- (NSArray *)colorsForPixelsAtPoints:(NSArray *)pointValues
{
NSMutableArray *colors = [NSMutableArray array];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Pinpoint individual pixels from the drawn view.
for (NSValue *pointValue in pointValues)
{
// Setup variables
unsigned char pixelData[4] = {0, 0, 0, 0};
CGSize imageSize = self.size;
CGPoint point = [pointValue CGPointValue];
// Create graphics context
CGContextRef colorContext = CGBitmapContextCreate(pixelData, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGContextSetBlendMode(colorContext, kCGBlendModeCopy);
CGContextTranslateCTM(colorContext, -point.x, (point.y - imageSize.height));
// Draw image
CGRect colorFrame = CGRectMake(0, 0, imageSize.width, imageSize.height);
CGContextDrawImage(colorContext, colorFrame, [self CGImage]);
// Get color information
UIColor *pixelColor = [UIColor colorWithRed: (pixelData[0] / 255.0)
green: (pixelData[1] / 255.0)
blue: (pixelData[2] / 255.0)
alpha: 1];
[colors addObject: pixelColor];
// Clean up
CGContextRelease(colorContext);
}
// Clean up
CGColorSpaceRelease(colorSpace);
return colors;
}
我想优化所需的时间。
我目前想知道将CGBitmapContextCreate
行移到for循环之前,以及如何使其工作。
任何其他加快这一点的想法都会受到赞赏。
答案 0 :(得分:1)
请参阅:How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?
您可以更改方法以读取不同坐标处的像素,而不是读取多个连续像素:
...
// Now your rawData contains the image data in the RGBA8888 pixel format.
for (int ii = 0 ; ii < [pointValues count] ; ++ii)
{
NSValue *pointValue = [pointValues objectAtIndex:ii]
CGPoint point = [pointValue CGPointValue];
int 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;
UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
[result addObject:acolor];
}
...
还要确保你的点在整数坐标上,否则你可能会遇到奇怪的结果!