HOW TO CONVERT MATRIX TO UIIMAGE?

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
iPhone  Ios 
 1010  View(s)
Ratings:
Rate this:

I need to convert a matrix representing a b/w image to UIImage.

For example:

A matrix like this (just the representation). This image would be the symbol '+'

001

110

0101

This matrix represents an image in black and white, where black is 0 and white is 1. I need to convert this matrix to UIImage. In this case width would be 3 and height would be 3

  1. Ankita Pandey

    Post:183

    Points:1285
    Re: How to Convert matrix to UIImage?

    In order to convert a matrix to UIImage :

    CGSize size = CGSizeMake(lines, columns);
    UIGraphicsBeginImageContextWithOptions(size, YES, 0);

    for (int i = 0; i < lines; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            // Choose color to draw 
            if ( matrixDraw[i*lines + j] == 1 ) {

                [[UIColor whiteColor] setFill];

            } else {

                // Draw black pixel
                [[UIColor blackColor] setFill];            
            }

            // Draw just one pixel in i,j
            UIRectFill(CGRectMake(i, j, 1, 1)); 

        }
    }

    // Create UIImage with the current context that we have just created
    UIImage *imageFinal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    Basically what we are doing is :

    Create a context with the size of our image

    Looping for each pixel to see the value. Black is 0 and white is 1. So depends on the value, we set the color.

    The most important function :

      UIRectFill(CGRectMake(i,j,1,1));
    This function let us to fill a pixel in the i,j position with width and height (1 both cases for fill one single pixel)

    Finally we create an UIImage with the current context and we call to finish the image context.
    Hope it helps someone!

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!