46
votes

I need to crop a UIImage, taken with the device camera, so that it fits inside another UIImage, which represents a frame (with rounded borders and so on). Check the image below:

enter image description here Using Aspect Fill

enter image description here Using Aspect Fit

So, what I need is to remove the image excess that is out of the frame bounds. I tried using UIBezierPath, CGImageRef and other methods that I Googled but I'm not finding a solution for this.

4
are you creating the frame programmatically or inside IB?sergio
The UIImageViews are within a xib fileCainaSouza
I got it using this How to Answer[1]! Thanks for your attention to help me! [1]: stackoverflow.com/questions/603907/uiimage-resize-then-cropCainaSouza
Have you tried clipsToBounds?James P
@CainaSouza you should accept the answer you deem to be correctPier-Luc Gendreau

4 Answers

128
votes

In Interface Builder, use the following configuration:

enter image description here

There are two important settings, namely:

  1. Mode: Aspect Fill

  2. Clip Subviews

It can also be done programmatically:

[imageView setContentMode:UIViewContentModeScaleAspectFill];
[imageView setClipsToBounds:YES];

This will correctly fill the view with the image, keep its aspect ratio and hide what doesn't fit.

4
votes

make a IBOutlet in your controller.

@property (retain)IBOutlet UIImageView* imageView;

and in -(void) viewDidLoad set

imageView.layer.masksToBounds = YES;
1
votes

In interface Builder, access the Mode menu inside of the detail pane (the fourth one) and choose the right one for your UIImageView (I guess "center" or "aspect fit").

enter image description here

OLD ANSWER:

You can use the contentGravity property of CALayer to make it work

A constant that specifies how the layer's contents are positioned or scaled within its bounds.

       @property(copy) NSString *contentsGravity
-1
votes

Use an UIImageView and do

imageView.contentMode = UIViewContentModeScaleAspectFit;