iOS 在 UIView 中绘制像素

标签 ios objective-c graphics opengl-es drawing

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

做这件事的最佳方法是什么,例如,整个过程是每秒 10 帧实时完成的?

最佳答案

使用下面的方法从您的二维数组创建一个 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;
}

关于iOS 在 UIView 中绘制像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25123607/

相关文章:

javascript - 以鼠标位置为中心的图像缩放

Swift 中带有普通和粗体文本标签的 iOS 选择器 View

ios - 在Objective-C中快速解析联系人对象的电话号码

objective-c - 为什么 iOS 无法使用 class_getProperty 函数获取类 UIView 的 subview 属性?

ios - 在 iPhone 5s 64 位上运行 32 位库

java - 如何获取 Swing 小部件上字体的底部位置?

cocoa-touch - UINavigationController:将通用填充/边距应用于所有弹出 View Controller 的 View

ios - Magento 2 luma iphone 响应式菜单

python - 无法使用 SSZipArchive 在 iOS9 中解压缩大型 zip 文件 (3.3GB)

algorithm - 从矩形绘制椭圆