iPhone App - Display pixel data present in buffer on screen

蓝咒 提交于 2019-12-04 23:29:49

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