Search code examples
iosuiimageviewcropshapes

Cropping ImageView in the Shape of Another ImageView


How can I crop my imageView into a bubble shape which I have the image in my project.


Solution

  • Following is simple code for resizing or crop image, you need to just pass height or width for image as you want:

    For Get Croped Image:

    UIImage *croppedImg = nil;
    CGRect cropRect = CGRectMake(AS YOu Need);
    croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];
    

    Use following method that return UIImage (as You want size of image)

    - (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
        {
            //CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);
    
            CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
            UIImage *cropped = [UIImage imageWithCGImage:imageRef];
            CGImageRelease(imageRef);
    
            return cropped;
        }
    

    Here you get Croped Image that return by above method;

    OR RESIZING

    And also Use following method for specific hight and width with image for Resizing UIImage:

    + (UIImage*)resizeImage:(UIImage*)image withWidth:(int)width withHeight:(int)height
    {
        CGSize newSize = CGSizeMake(width, height);
        float widthRatio = newSize.width/image.size.width;
        float heightRatio = newSize.height/image.size.height;
    
        if(widthRatio > heightRatio)
        {
            newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
        }
        else
        {
            newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
        }
    
    
        UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
        [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    

    This method return NewImage, with specific size that you want.