Gopikrishna
Gopikrishna

Reputation: 99

How to crop an image into polygon shape in iOS?

I want to crop an image which is on the UIImageview into any shape

Upvotes: 2

Views: 1962

Answers (2)

justin
justin

Reputation: 104698

You can use a CGImageMask.

A sample exists in the class QuartzMaskingView of Apple's QuartzDemo.

Upvotes: 0

Sverrisson
Sverrisson

Reputation: 18157

You set the clipping path and voila:

// Load image thumbnail
    NSString *imageName = [self.picArray objectAtIndex:indexPath.row];
    UIImage *image = [UIImage imageNamed:imageName];        
    CGSize imageSize = image.size;
    CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);    

    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    // Create the clipping path and add it
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:imageRect cornerRadius:5.0f];
    [path addClip];
    [image drawInRect:imageRect];
    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

This code loads an image and creates a path by rounding the rectangle, the result is that the final image has been clipped, i.e. rounded corners. RoundedImage is the result.

Upvotes: 2

Related Questions