Deep2012
Deep2012

Reputation: 55

Cropping ellipse using core image in ios

I want to crop an ellipse from an image in ios. Using core image framework, I know know to crop a reactangular region.

Using core graphics, I am able to clip the elliptical region. But, the size of the cropped image is same as the size of the original image as I am applying mask to area outside the ellipse.

So, the goal is to crop the elliptical region from an image and size of cropped image won't exceed the rectangular bounds of that image.

Any help would be greatly appreciated. Thanks in advance.

Upvotes: 1

Views: 876

Answers (1)

Jonathan Cichon
Jonathan Cichon

Reputation: 4406

You have to create a context in the correct size, try the following code:

- (UIImage *)cropImage:(UIImage *)input inElipse:(CGRect)rect {
    CGRect drawArea = CGRectMake(-rect.origin.x, -rect.origin.y, input.size.width, input.size.height);

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, rect.size.width, rect.size.height));
    CGContextClip(ctx);

    [input drawInRect:drawArea];

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Maybe you have to adjust the drawArea to your needs as i did not test it.

Upvotes: 2

Related Questions