UIViewContentModeScaleAspectFit in UIImageView does not work correctly - ios

I try to fit an Image into my UIImageView which is called imgBack
I define my UIImageView in the header as IBOutlet
IBOutlet UIImageView *imgBack;
in my viewDidLoad function I set the contentMode like this:
imgBack.contentMode = UIViewContentModeScaleAspectFit;
But after I load an image into imgBack like this:
imgBack.image = [UIImage imageWithContentsOfFile: imagePath];
it does not scale to fit into the imageview
This is the picture I load into imgBack:
image i try to load
And this is how it looks like in the view: image in UIImageView
As you see, the image does not fit into the View.
Does anyone know why?

If changing ImageView contentMode does not work for you, then you can try to resize the image to fit in Image View with help of following code
UIImage *originalImage = [UIImage imageWithContentsOfFile: imagePath];
imgBack.image = [self resizeImage: originalImage imageSize: imgBack.size];
and add this code to your ViewController
-(UIImage*)resizeImage:(UIImage *)image imageSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0,0,size.width,size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//here is the scaled image which has been changed to the size specified
UIGraphicsEndImageContext();
return newImage;
}

Attach the image to UIImageView first and then change the content mode
imgBack.image = [UIImage imageWithContentsOfFile: imagePath];
imgBack.contentMode = UIViewContentModeScaleAspectFill;
imgBack.clipsToBounds = YES;

below are the mode try and check
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit, // contents scaled to fit with fixed aspect. remainder is transparent
UIViewContentModeScaleAspectFill, // contents scaled to fill with fixed aspect. some portion of content may be clipped.
UIViewContentModeRedraw, // redraw on bounds change (calls -setNeedsDisplay)
UIViewContentModeCenter, // contents remain same size. positioned adjusted.
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,

Related

How to fit an image on a uiview programmatically

I added a uiview as a subview on a view controller programmatically (called contentView). I also added an image on that uiview programmatically. Every time I run the app on the iPad the image is stretched! How do I fix the image so that it fits the iPad screen but doesn't stretch the image? I know the drawInRect is what is stretching the image. So how do I fix that?
Here is my code:
UIGraphicsBeginImageContextWithOptions(self.contentView.bounds.size, self.contentView.opaque, 0.0);
[[UIImage imageNamed:#"menu image 2.JPG"] drawInRect:self.contentView.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.contentView addSubview:imageView];
UIImageView has a property called contentMode which determines how the image layout is handled in the view context. contentMode is of type UIViewContentMode.
The default value is UIViewContentModeScaleToFill which stretches the image without respecting the aspect ratio. I am assuming it is the changing aspect ratio that is causing the issue.
If you wish to scale the image, but keep the aspect ratio, you have two options:
UIViewContentModeScaleAspectFit: This will show the image scaled to fill the view, but not clip any contents (if the aspect ratio doesn't match view size, it will show either horizontal or vertical bands)
UIViewContentModeScaleAspectFill: This will scale the image to fill the view entirely, without any bands - this will result in content being clipped if the image ratio doesn't match the view ratio.
To set the contentMode on the image view in Objective-C, use the following syntax:
UIImage *image = [UIImage imageNamed:#"menu image 2.JPG"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.contentMode = UIViewContentModeScaleAspectFill;
...
You should not need to use the custom context drawing for this to work anymore (thanks to Losiowaty for asking me about this).
Change code as below
UIImage *image = [UIImage imageNamed:#"menu image 2.JPG"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.contentView addSubview:imageView];
I guess your self.contentView.bounds is not having the same aspect ratio as your menu image 2.JPG . For an experiment, please try looking at the menu image 2.JPG's resolution. For example if it is 300x150, it's aspect ratio is (300/150 = 2:1). Set your self.contentView.bounds to this aspect ratio and draw the image and check the results. It will not stretch.
Please add this Single Line of code in your project
yourImage .contentMode = UIViewContentModeScaleAspectFit;

Set image in UIImageView with original Dimension in ios

My UIImageView with constant Width*Height is 100*100 on UIView, But image i want to show in this UIImageView is 25*25 (original dimension ).
I don't want to stretch image. i try UIImageView ContentMode property but did't work.
This i don't want.tried sizeToFit and aspectCenter mode.
I need following result,For small images
How to do that(With out stretching original image dimension and constant UIImageView dimension).What will be case if image is bigger than UIImageView ? Thanks in advance.
Try this
(Objective-C):
imageView.contentMode = UIViewContentModeCenter;
(Swift):
imageView.contentMode = UIViewContentMode.Center;
Call - sizeToFit
That should do exactly what you need.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/sizeToFit
you should try this
imageView.contentMode = UIViewContentModeScaleAspectFit;
no matter image is small or big it will scale the image.
if you don't want to stretch image than you have to resize UIImageView to image size
You can obtain image size from UIImage.
for eg
UIImage *image = [UIImage imageNamed:#"imageName"];
float imgHeight = image.size.height;
float imgWidth = image.size.width;

UIImageView contentMode Top

I've got an image that I need crop. To do this, I wanted to use the contentMode (set it to Top/TopLeft instead of Aspect Fit) but when I'm doing this, the image go back to it's real size (and not the size I gave to it). So my question is :
How to crop the bottom of my image retaining its size ?
Thanks a lot.
May be you have to set the rect for the imageView
imageView is the instance of UIImageView
Let the rectangle to be cropped is croppedRect
CGImageRef imageRef = CGImageCreateWithImageInRect([imageView.image CGImage], croppedRect);
[imageView setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);

Crop a UIImage according to visible area in a UIImageView UIViewContentMode

I am setting a UIImage inside a UIImageView. The UIImageView can have its content mode set to one of the available ones:
typedef NS_ENUM(NSInteger, UIViewContentMode) {
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit, // contents scaled to fit with fixed aspect. remainder is transparent
UIViewContentModeScaleAspectFill, // contents scaled to fill with fixed aspect. some portion of content may be clipped.
UIViewContentModeRedraw, // redraw on bounds change (calls -setNeedsDisplay)
UIViewContentModeCenter, // contents remain same size. positioned adjusted.
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
};
I would like to crop the image such that the proportions will match the content mode.
How is this achieved?
I don't this you can use the content mode to achieve this. Please try with below core graphics code:
- (UIImage *)cropVisiblePortionOfImageView:(UIImageView *)imageView {
CGFloat zoomScaleX=imageView.frame.size.width/initialWidth;
CGFloat zoomScaleY=imageView.frame.size.height/initialHeight;
CGSize zoomedSize=CGSizeMake(initialWidth*zoomScaleX,initialHeight*zoomScaleY);
UIGraphicsBeginImageContext(zoomedSize);
[imageView.image drawInRect:CGRectMake(0, 0, zoomedSize.width, zoomedSize.height)];
UIImage *zoomedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIGraphicsBeginImageContext(CGSizeMake(initialWidth, initialHeight));
[zoomedImage drawAtPoint:CGPointMake(imageView.frame.origin.x, imageView.frame.origin.y)];
UIImage *cropedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return cropedImage;
}

How to fill the background with image in landscape in IOS?

What I'm doing is creating filling in a view's background with an image returned from a UIImagePickerController. The image fills fine in portrait mode; however, the image will repeat when filled as background in landscape mode, but I have no idea why this is occuring. This is a private method I use to resize my image.
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize landscape:(BOOL)landscape {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
When this method is called the newsize parameter is equal to the views bounds size (self.view.bounds.size). The size is accessed after the view's transformation to landscape, but the image doesn't properly.
This is the code that is called right after getting an image from the UIImagePickerController.
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (image.size.width > image.size.height) {
self.view.transform = CGAffineTransformRotate(self.view.transform, M_PI_2);
self.composition.landscapemode = YES;
} else {
self.composition.landscapemode = NO;
}
self.composition.image = [NewCompositionViewController imageWithImage:image scaledToSize:self.view.bounds.size landscape:self.composition.landscapemode];
self.view.backgroundColor = [UIColor colorWithPatternImage:self.composition.image];
[self dismissViewControllerAnimated:YES completion:nil];
}
[UIColor colorWithPatternImage:] is meant for tiling images, so it's behaving as it should.
I would recommend creating a UIImageView with screen-sized frame, setting an image to it, and adding it as subview:
UIImageView *backgroundImage = [[UIImageView alloc] initWithFrame:self.view.frame];
[backgroundImage setImage:self.composition.image];
// choose best mode that works for you
[backgroundImage setContentMode:UIViewContentModeScaleAspectFill];
[self.view insertSubview:backgroundImage atIndex:0];
//OR
[self.view addSubview:backgroundImage];
[self.view sendSubviewToBack:backgroundImage];
once it's added, you can rotate it and experiment with autoresizing masks to make sure it's displayed properly for all orientations. Exact method would depend on if you are using auto-layout or not.
UIViewContentModeScaleAspectFill may be more appropriate here than UIViewContentModeScaleAspectFit since the image is filling a background view. AspectFit will maintain the image's aspect ratio and make the entire image fit in the space, which may leave portions of the view transparent. AspectFill also maintains aspect ratio, but will fill the entire view and clip any portions of the image that don't match the view bounds.
I've been able to apply an "aspect fit" UIImage to a UIView background by combining a few AVFoundation and UIKit APIs. Here's one example:
UIImage *image = [UIImage imageWithContentsOfFile:self.desiredBackgroundImageFilePathString];
UIGraphicsBeginImageContext(self.drawingImage.frame.size);
[image drawInRect:AVMakeRectWithAspectRatioInsideRect(image.size, self.drawingImage.bounds)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.drawingImage.backgroundColor = [UIColor colorWithPatternImage:image];
This flows through a few simple, but important steps:
Generate a UIImage from a file (or whatever).
Define the context of the image (the desired UIView for the background) with UIGraphicsBeginImageContext().
Use drawInRect in combination with AVMakeRectWithAspectRatioInsideRect to scale the image. Provide AVMakeRect...() with the image's .size and the bounds of the target UIView.
Apply the resized image to the desired image context.
Apply your now-resized image to the .backgroundColor of the target UIView using colorWithPatternImage.
I'm able to swap out images with both landscape and portrait aspect ratios without alignment or clipping issues using this code.

Resources