vondip
vondip

Reputation: 14029

IOS - Get binary mask (bitmask) from UIBeizerPath

I am building an IOS application. In my app I have an image a user can crop manually. After a user crops the image I wish to save the mask information in a binary form.

I need it to be a binary image, not only as an NSCoding form, as I will need to use the mask information on other platforms (not just IOS).

How can I convert the UIBezierPath to a binary mask array.

Upvotes: 0

Views: 258

Answers (1)

Tutankhamen
Tutankhamen

Reputation: 3562

First, you must rasterize (stroke/fill) your UIBeizerPath to your image context and then you can manipulate with its raster data. Here is an example how to rasterize UILabel:

UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, siz.w, siz.h)];
label.text = [[NSString alloc] ... ];
label.font = [UIFont boldSystemFontOfSize: ... ];

UIGraphicsBeginImageContext(label.frame.size);
[label.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* layerImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Get Image size
GLuint width = CGImageGetWidth(layerImage.CGImage);
GLuint height = CGImageGetHeight(layerImage.CGImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

// Allocate memory for image
void *imageData = malloc( height * width * 4 );
CGContextRef imgcontext = CGBitmapContextCreate(
                                                imageData, width, height, 8, 4 * width, colorSpace,
                                                kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Little );
CGColorSpaceRelease( colorSpace );
CGContextClearRect( imgcontext,
                   CGRectMake( 0, 0, width, height ) );
CGContextTranslateCTM( imgcontext, 0, height - height );
CGContextDrawImage( imgcontext,
                   CGRectMake( 0, 0, width, height ), layerImage.CGImage );

// Create image

[.. here you can do with imageData whatever you want ..]

image.InitImage(imageData, width * height * 4, width, height, iResource_Image::ImgFormat_RGBA32);



// Release context
CGContextRelease(imgcontext);
free(imageData);
[label release];

Upvotes: 2

Related Questions