Im trying to fit an image into uiimageview, the images are downloaded and loaded dinamically, and theres only one resolution available for ios and android apps.
So, i need images to keep aspect ratio and scale to width, i set UIImageView
content mode to
UIViewContentModeScaleAspectFill
, but it centers image, so it goes out of screen for both top and bottom, images will be designed so that the bottom is unnecessary.
How can i align the image to the top-left corner?
And can UIImageView scale to width for me too? or how can i do it?
Thanks in advance.
EDIT:
I tried setcliptobounds
and that cuts the image to imageview size, thats not my problem.
UIViewContentModeTopLeft
is working well, but now i cant apply UIViewContentModeScaleAspectFill
, or can i apply both?
Effective approach without stretching image Swift 4 // Method to resize image func resize(image: UIImage, toScaleSize:CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(toScaleSize, true, image. scale) image. draw(in: CGRect(x: 0, y: 0, width: toScaleSize. width, height: toScaleSize.
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
The first step is to drag the UIImageView onto your view. Then open the UIImageView properties pane and select the image asset (assuming you have some images in your project). You can also configure how the underlying image is scaled to fit inside the UIImageView.
You could scale the image to suit the image view's width.
You could use a category on UIImage
that creates a new image with chosen width.
@interface UIImage (Scale)
-(UIImage *)scaleToWidth:(CGFloat)width;
@end
@implementation UIImage (Scale)
-(UIImage *)scaleToWidth:(CGFloat)width
{
UIImage *scaledImage = self;
if (self.size.width != width) {
CGFloat height = floorf(self.size.height * (width / self.size.width));
CGSize size = CGSizeMake(width, height)
// Create an image context
UIGraphicsBeginImageContext(size);
// Draw the scaled image
[self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
// Create a new image from context
scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// Pop the current context from the stack
UIGraphicsEndImageContext();
}
// Return the new scaled image
return scaledImage;
}
@end
This way you can use it to scale the image
UIImage *scaledImage = [originalImage scaleToWidth:myImageView.frame.size.width];
myImageView.contentMode = UIViewContentModeTopLeft;
myImageView.image = scaledImage;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With