Question

I am using following code to make an image oval shape.

 UIImage * fooImage = image;

CGRect imageRect = CGRectMake(0, 0, 291, 130);

UIGraphicsBeginImageContextWithOptions(imageRect.size,NO,0.0);
// create a bezier path defining rounded corners
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(0.0, 0.0, CGRectGetWidth(img_blank.frame), CGRectGetHeight(img_blank.frame))];

// use this path for clipping in the implicit context
[path addClip];
// draw the image into the implicit context
[fooImage drawInRect:imageRect];
// save the clipped image from the implicit context into an image
UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
       img_blank.image=maskedImage;

Here image_blank is the UIImage which I am using, if image with greater width and less height comes then it will not strech. If I change the values, I won't get an oval shape that fits my UIImageview(img_blank).

Was it helpful?

Solution

This issue is that your rect size and your image size don't match.

When you: [fooImage drawInRect:imageRect];

the image will be drawn skewed into that rectangle, which you've defined as CGRectMake(0, 0, 291, 130);

To get it to work, you need to create a second rectangle that expands the oval's rectangle to match the image'a width/height ratio. You can then use this second rectangle to draw the image so that the image will aspect-fill the oval.

This is some pseudo code that I've used in the past for similar problems:

// get the size of the image that we want to scale
CGSize imageSize = imageToDraw.size;
// get the size of the canvas we're trying to fill
CGSize canvasSize = imageRect.size;
// we need to see how the ratio of image width & height compare to the canvas
CGFloat horizontalRatio = canvasSize.width / imageSize.width;
CGFloat verticalRatio = canvasSize.height / imageSize.height;
// pick the ratio that requires the most scaling
CGFloat ratio = MAX(horizontalRatio, verticalRatio); //AspectFill
// calculate the size that we should draw the image so that it could fill
// the entire canvas with an aspect-fill rule
CGSize aspectFillSize = CGSizeMake(imageSize.width * ratio, imageSize.height * ratio);

// now draw the image, centering it and filling the canvas
[imageToDraw drawInRect:CGRectMake((canvasSize.width-aspectFillSize.width)/2,
                                           (canvasSize.height-aspectFillSize.height)/2,
                                            aspectFillSize.width,
                                            aspectFillSize.height)];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top