Reputation: 59
How to make photos that are loaded from the site in containers scaled in height and width in my IOS app? In my application some of the photos are stretched (second one from the start), how to fix it?
Upvotes: 1
Views: 100
Reputation: 6940
I think you problem is actual size of image, that may not be actual square or rectangle. In that case you may want to use this 2 approaches :
1) yourImageView.contentMode = UIViewContentModeScaleAspectFit;
//That keeps an entire image in frame but cut borders
2) yourImageView.contentMode = UIViewContentModeScaleAspectFill;
//That fills whole frame with image but cut off sides
For proper sizing your image in frame i recommend use category:
- (UIImage*)resizedImageWithBounds:(CGSize)bounds;
- (UIImage*)resizedImageWithBounds:(CGSize)bounds{
// Based on code by Trevor Harmon
CGFloat horizontalRatio = bounds.width/self.size.width;
CGFloat verticalRatio = bounds.height/self.size.height;
CGFloat ratio = MIN(horizontalRatio,verticalRatio);
CGSize newSize = CGSizeMake(self.size.width*ratio, self.size.height*ratio);
UIGraphicsBeginImageContextWithOptions(newSize, YES, 0);
if (newSize.width >66){
newSize.width = 66;
}
if (newSize.height > 66){
newSize.height = 66;
}
[self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
In this code 66 stand for width/height of an image.
Hope it helps.
Upvotes: 1
Reputation: 2105
instead of using width:100%
and height:100%
on the images, try to use max-width:100%
and max-height:100%
. This way, your images will keep their ratio but may leave blank space.
To avoid blank spaces you could show your images in CSS with background-image:url('url_of_image')
and background-size:cover
. In this way, the images will fill the div, keeping their ratio but may be of greater size.
Upvotes: 2
Reputation: 71150
One technique using CSS would be to assign the images as the background of an element, then scale accordingly:
.imgContainer{
background-image:url(myImage.jpg); /* <--- add the image as the background */
background-size:cover; /* <--- scale the image maintaining proportions */
background-position:center center; /* <--- center the image */
}
More on background-size
from MDN
The background-size CSS property specifies the size of the background images. The size of the image can be fully constrained or only partially in order to preserve its intrinsic ratio.
cover: This keyword specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area.
..and background-position
Upvotes: 2