Question

I have the source code for a video decoder application written in C, which I'm now porting on iphone.

My problem is as follows:

I have RGBA pixel data for a frame in a buffer that I need to display on the screen. My buffer is of type unsigned char. (I cannot change it to any other data type as the source code is too huge and not written by me.)

Most of the links I found on the net say about how to "draw and display pixels" on the screen or how to "display pixels present in an array", but none of then say how to "display pixel data present in a buffer".

I'm planning to use quartz 2D. All I need to do is just display the buffer contents on the screen. No modifications! Although my problem sounds very simple, there isn't any API that I could find to do the same. I couldn't find any appropriate link or document that was useful enough.

Kindly help! Thanks in advance.

Was it helpful?

Solution

You can use the CGContext data structure to create a CGImage from raw pixel data. I've quickly written a basic example:

- (CGImageRef)drawBufferWidth:(size_t)width height:(size_t)height pixels:(void *)pixels
{
    unsigned char (*buf)[width][4] = pixels;


    static CGColorSpaceRef csp = NULL;
    if (!csp) {
        csp = CGColorSpaceCreateDeviceRGB();
    }

    CGContextRef ctx = CGBitmapContextCreate(
        buf,
        width,
        height,
        8, // 8 bits per pixel component
        width * 4, // 4 bytes per row
        csp,
        kCGImageAlphaPremultipliedLast
    );

    CGImageRef img = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    return img;
}

You can call this method like this (I've used a view controller):

- (void)viewDidLoad
{
    [super viewDidLoad];

    const size_t width = 320;
    const size_t height = 460;

    unsigned char (*buf)[width][4] = malloc(sizeof(*buf) * height);

    // fill up `buf` here
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            buf[y][x][0] = x * 255 / width;
            buf[y][x][1] = y * 255 / height;
            buf[y][x][2] =   0;
            buf[y][x][3] = 255;
        }
    }

    CGImageRef img = [self drawBufferWidth:320 height:460 pixels:buf];
    self.imageView.image = [UIImage imageWithCGImage:img];
    CGImageRelease(img);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top