【问题标题】:Speeding up checking pixel color at point加快检查点的像素颜色
【发布时间】:2014-05-28 17:14:44
【问题描述】:

我有这段代码,它主要使用 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 循环之前,以及如何使其工作。

如果您有任何其他加快速度的想法,我们将不胜感激。

【问题讨论】:

    标签: objective-c c uiimage cgcontext pixels


    【解决方案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];
    }
    ...
    

    还要确保您的点在整数坐标上,否则您可能会遇到奇怪的结果!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 2020-04-27
      • 2013-12-05
      相关资源
      最近更新 更多