Michael Chourdakis
Michael Chourdakis

Reputation: 11158

subimage from UIImage

I 've a PNG loaded into an UIImage. I want to get a portion of the image based on a path (i.e. it might not be a rectangular). Say, it might be some shape with arcs, etc. Like a drawing path.

What would be the easiest way to do that?

Thanks.

Upvotes: 1

Views: 589

Answers (2)

Lance
Lance

Reputation: 9012

I haven't run this, so it may not be perfect but this should give you an idea.

UIImage *imageToClip = //get your image somehow
CGPathRef yourPath = //get your path somehow
CGImageRef imageRef = [imageToClip CGImage];

size_t width = CGImageGetWidth(imageRef);  
size_t height = CGImageGetHeight(imageRef);
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, CGImageGetColorSpace(imageRef), kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextAddPath(context, yourPath);
CGContextClip(context);

CGImageRef clippedImageRef = CGBitmapContextCreateImage(context);  
UIImage *clippedImage = [UIImage imageWithCGImage:clippedImageRef];//your final, masked image

CGImageRelease(clippedImageRef);
CGContextRelease(context);

Upvotes: 2

Danyun Liu
Danyun Liu

Reputation: 3092

The easiest way to add a category to the UIImage with follow method:

-(UIImage *)scaleToRect:(CGRect)rect{
// Create a bitmap graphics context
// This will also set it as the current context
UIGraphicsBeginImageContext(size);

// Draw the scaled image in the current context
[self drawInRect:rect];

// Create a new image from current context
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

// Pop the current context from the stack
UIGraphicsEndImageContext();

// Return our new scaled image
return scaledImage;

}

Upvotes: 1

Related Questions