0

コンテキストを作成し、次にグラデーションを作成しました。その後、私は文脈に沿って描いています。次に、コンテキストからグラデーション画像を受け取りましたが、それは正しいです。デバッガーで確認できます。しかし、特定の値のピクセルの色を取得しようとすると、正しくありません。助けていただければ幸いです。これがコードです。

- (UIColor*) getColorForPoint: (CGPoint) point imageWidth: (NSInteger) imageHeight
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    // create a gradient

    CGPoint startPoint = CGPointMake(0, 0);
    CGPoint endPoint = CGPointMake(imageHeight, 0);

    // create a bitmap context to draw the gradient to, 1 pixel high.
    CGContextRef context = CGBitmapContextCreate(NULL, imageHeight, 1, 8, 0, colorSpace,     kCGImageAlphaPremultipliedLast);

    // draw the gradient into it
    CGContextAddRect(context, CGRectMake(0, 0, imageHeight, 1));
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);

    // Get our RGB bytes into a buffer with a couple of intermediate steps...
    //      CGImageRef -> CFDataRef -> byte array
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    CGDataProviderRef provider = CGImageGetDataProvider(cgImage);
    CFDataRef pixelData = CGDataProviderCopyData(provider);

    // cleanup:
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(cgImage);
    CGContextRelease(context);

    const UInt8* data = CFDataGetBytePtr(pixelData);

    // we got all the data we need.
    // bytes in the data buffer are a succession of R G B A bytes

    CGFloat y = 100 * point.y / imageHeight;
    int pixelIndex = (int)y * 4; // 4 bytes per color
    UIColor *color = [UIColor colorWithRed:data[pixelIndex + 0]/255.0f
                                 green:data[pixelIndex + 1]/255.0f
                                  blue:data[pixelIndex + 2]/255.0f
                                 alpha:data[pixelIndex + 3]/255.0f];

    // done fetching color data, finally release the buffer
    CGDataProviderRelease(provider);

    return color;
}
4

1 に答える 1