IOS to draw pixels in UIView

I have a 2D array of RGB values ​​(or any such data container) that I need to write to a UIView that is currently being displayed to the user. An example would be: when using the capture output from the camera, I run some algorithms to identify the objects and then highlight them with custom RGB pixels.

What is the best way to do this since this is all done in real time every 10 frames per second, for example?

+3


source to share


1 answer


Use below method to create UIImage from your 2D array. Then you can display this image using 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;
}

      

+2


source







All Articles