iPhone App - Display pixel data present in buffer on screen

余生长醉 提交于 2019-12-10 00:34:41

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/15463719/iphone-app-display-pixel-data-present-in-buffer-on-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!