UIImageView content mode is not working - ios

I have a large image (1920*1080), and a smaller UIImageView (320*568) that scaled to full screen size in the story board.
Now I want to display this large image full screen size, but fit to the UIImageView.
I have tried all the content mode, but they are all not working. Every time it just shows the top left part of the image full screen sized.
[self.imageView setFrame:self.view.bounds];
[self.imageView setContentMode:UIViewContentModeScaleAspectFit] ;
[self.imageView setImage:image] ;
[self.view insertSubview:_imageView aboveSubview:_previewView] ;
So what might be wrong in my case? could that be a Xcode story board configuration error ?
thanks.

If you are seeing only the image top corner in your ImageView, then the possible reasons are: Your ImageView frame is out of screen size OR Content Mode is not set. In your code you are setting the frame as the bounds of the superview. If your are using Auto-layout, check the auto-layout are set properly. If this is ok, then try setting UIImageView ContentMode before setting the frame.
// Setting the content mode.
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
// Now set the frame.
[self.imageView setFrame:self.view.bounds];
Other solution is you can downscale your image to fit your ImageView. For that you can use the following function:
- (UIImage *)scaleImage:(UIImage *)orginalImage
{
float widthFactor = photoImageView.frame.size.width / orginalImage.size.width;
CGSize destinationSize = CGSizeMake(orginalImage.size.width * widthFactor,orginalImage.size.height * widthFactor);
UIGraphicsBeginImageContext(destinationSize);
[orginalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
photoImageView.image = scaledImage;
return scaledImage;
}

There is a problem that CIImage does somehow not respect contentMode (at least on some devices / iOS versions). Convert CIImage to a CGImage to make this work.
Swift 3 code:
func convertCIImageToCGImage(inputImage: CIImage) -> CGImage?
{
let context = CIContext(options: nil)
if let cgImage = context.createCGImage(inputImage, from: inputImage.extent)
{
return cgImage
}
return nil
}

Try this
[self.imageView setFrame:self.view.bounds];
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
self.imageView.clipsToBounds = YES;
[self.imageView setImage:image] ;
[self.view insertSubview:_imageView aboveSubview:_previewView] ;
Working fine .. :)

In my case, i solved this removing some constraints that resize the imageview that i set by error.
Check your imageview constraints, try removing all of them

Related

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 displaying in wrong dimensions

I'm loading an UIImage into a UIImageView and setting the dimensions of the image to be the same as of the UIImageView which was created in storyboard and is 60x60 by default. Code-wisely, everything works, the debug says that the dimensions of image and imageView are both 60px, however looking at the simulator, you can obviously see a rectangle rather than a box. Where is the problem?
Image loading code:
- (void)viewWillAppear:(BOOL)animated
{
NSString *userImageURL = [NSString stringWithFormat:#"https://graph.facebook.com/TheOfficialKanyeWest/picture?"];
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:userImageURL]];
UIImage* profilePic = [UIImage imageWithData:data];
profilePic = [self imageWithImage:profilePic scaledToSize:profilePictureImageView.frame.size];
[profilePictureImageView setImage:profilePic];
//[profilePictureImageView sizeToFit];
NSLog(#"\n\nView:\nWidth: %f\nHeight: %f\n\nImage:\nWidth: %f\nHeight: %f\n", profilePictureImageView.frame.size.width, profilePictureImageView.frame.size.height, profilePic.size.width, profilePic.size.height);
}
Custom function for resizing image:
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Also, the debug I put in the ViewDidAppear gives me:
View:
Width: 60.000000
Height: 60.000000
Image:
Width: 60.000000
Height: 60.000000
Edit:
Forgot to add screenshot
Solution
The code was absolutely fine. I failed to notice that my automatic constraints were causing the imageView to resize to the odd rectangular shape. I added my constraints manually and now it works well.
Pin width and height constraints of the imageView to 60 and 60 in story board don't use automatic constraints.
I have tried your code, in coding its absolutely right, but in storyboard there is any mistakes in autolayouts..
Move the code from viewWillAppear to viewDidAppear. In viewWillAppear your UIImageView is not set to its final frame.
Try your code in
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// put your code to here to set frame and size of imageview.
}

Fit image in UIImageView using UIViewContentModeScaleAspectFit

I'm facing a really weird problem with UIImageView, I was trying to set an image - which created by take the screenshot of the current view - to an ImageView with content mode is UIViewContentModeScaleAspectFit.
It worked fine when I set the image by the interface builder in the xib file or when I set the image created by [UIImage imageNamed:]. They both worked fine with UIViewContentModeScaleAspectFit.
But when I take the snap shot of a view and set the image to the image view, the image did not fit to the UIImageView. I've tried all the solutions I found on here like .ClipsToBound = YES but they didn't work at all. I'm really confused by now.
Here's the code when I take the screen shot and create the UIImage:
- (UIImage *)screenshotWithRect:(CGRect)captureRect
{
CGFloat scale = [[UIScreen mainScreen] scale];
UIImage *screenshot;
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, scale);
CGContextClipToRect (UIGraphicsGetCurrentContext(),captureRect);
{
if(UIGraphicsGetCurrentContext() == nil)
{
NSLog(#"UIGraphicsGetCurrentContext is nil. You may have a UIView (%#) with no really frame (%#)", [self class], NSStringFromCGRect(self.frame));
}
else
{
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
screenshot = UIGraphicsGetImageFromCurrentImageContext();
}
}
UIGraphicsEndImageContext();
return screenshot;
}
And when I set the image to the image view
UIImage* snap = [[UIImage alloc] init];
// start snap shot
UIView* superView = [self.view superview];
CGRect cutRect = [superView convertRect:self.cutView.frame fromView:_viewToCut];
snap = [superView screenshotWithRect:cutRect];
[self.view addSubview:self.editCutFrameView];
// end snap shot -> show edit view
[self.editCutFrameView setImage:snap];
Here's a picture compare the 2 results:
Many thanks for your help.
UPDATE: As #Saheb Roy mentioned about the size, I checked the image size and it's about 400x500px and the thumbnail.png's size is 512x512px so I think it's not about the size of the image.
This is because in the second case, the snapshot image is itself exactly that size as you can see. Hence the image is not being stretched or fitted accordingly.
Earlier images are fitting to screen accordingly as the images were bigger than the imageview but with different ratio or same than that of the image.
But the one where it is not fitting to the imageview, the image itself is of that much size, i.e. smaller than that of the imageview, hence it is NOT being fitted to the bounds.

Change UIImageView height to image height?

I have a UIImageView set up which will display an image determined by what the user selected in the previous table view.
This is how I am currently displaying my images:
if ([_TitleLabel.text isEqualToString:#"Dog"]) {
UIImage *image = [UIImage imageNamed:#"Dog.png"];
[imageView setImage:image];
}
Subsequent if statements follow displaying the different images for a different animal.
These images need to be of a different height, and I need to keep their proportionality. The width of all the images is 320 pts. The heights vary from anywhere between 1000pts to 2500pts. All images are located locally in the project. I want the height of the UIImageView to change to the height of image which corresponds to the animal selected by the user. Any ideas?
You can update the imageView's frame width and height using UIImage's width and height, like this:
if ([_TitleLabel.text isEqualToString:#"Dog"]) {
UIImage *image = [UIImage imageNamed:#"Dog.png"];
[imageView setImage:image];
// update image view frame width and height.
imageView.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, image.size.width, image.size.height);
}
Note:
Using UIViewContentModeScaleAspectFit will leave space between your image and the UIImageView boundary if the image is different aspect ratio to your UIImageView frame, which isn't likely what you want.
Nor will UIViewContentModeScaleAspectFill help, your image will become truncated within the frame of your imageView.
imageView.contentMode = UIViewContentModeCenter;
if (imageView.bounds.size.width > ((UIImage*)imagesArray[i]).size.width && imageView.bounds.size.height > ((UIImage*)imagesArray[i]).size.height) {
imageView.contentMode = UIViewContentModeScaleAspectFit;
}

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