iOS在UIView中绘制像素

时间:2014-08-04 16:46:37

标签: ios objective-c graphics opengl-es drawing

我有一个我需要写入UIView的RGB值(或任何此类数据容器)的2D数组,当前显示给用户。一个例子是 - 在使用摄像头的捕获输出时,我运行一些算法来识别对象,然后使用自定义的RGB像素突出显示它们。

最好的方法是什么,因为整个过程每秒每10帧实时完成一次?

1 个答案:

答案 0 :(得分:2)

使用以下方法从2D阵列创建UIImage。然后,您可以使用UIImageView显示此图像。

-(UIImage *)imageFromArray:(void *)array width:(unsigned int)width height:(unsigned int)height {
    /*
     Assuming pixel color values are 8 bit unsigned

     You need to create an array that is in the format BGRA (blue,green,red,alpha).  
     You can achieve this by implementing a for-loop that sets the values at each index. 
     I have not included a for-loop in this example because it depends on how the values are stored in your input 2D array.  
     You can set the alpha value to 255.
    */
    unsigned char pixelData[width * height * 4];

    // This is where the for-loop would be

    void *baseAddress = &pixelData;

    size_t bytesPerRow = width * 4;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);

    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage *image = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    return image;
}