I have this UIImageView
and I have the values of its max height and max width. What I want to achieve is that I want to take the image (with any aspect ratio and any resolution) and I want it to fit in the borders, so the picture does not exceed them, but it can shrink them as it wants. (marked red in the picture):
Right now the image fits the necessary size properly, but I have 2 worries: 1. The UIImageView
is not equal the size of the resized image, thus leaving red background (and I don't want that) 2. If the image is smaller that the height of my UIImageView
it is not resized to be smaller, it stays the same height.
Here's my code and I know its wrong:
UIImage *actualImage = [attachmentsArray lastObject]; UIImageView *attachmentImageNew = [[UIImageView alloc] initWithFrame:CGRectMake(5.5, 6.5, 245, 134)]; attachmentImageNew.image = actualImage; attachmentImageNew.backgroundColor = [UIColor redColor]; attachmentImageNew.contentMode = UIViewContentModeScaleAspectFit;
So how do I dynamically change the size not only of the UIImageView.image
, but of the whole UIImageView
, thus making its size totally adjustable to its content. Any help would be much appreciated, thanks!
The simplest way is to set the frame of your UIImageView and set the contentMode to one of the resizing options. I would NOT retain the result here. newImage will be autoreleased already, and it should up to the method that called this to retain it or not.
It reduces the image size to less than 100kb. It works proportionally! extension UIImage { class func scaleImageWithDivisor(img: UIImage, divisor: CGFloat) -> UIImage { let size = CGSize(width: img. size.
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
When you get the width and height of a resized image Get width of a resized image after UIViewContentModeScaleAspectFit, you can resize your imageView:
imageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight); imageView.center = imageView.superview.center;
I haven't checked if it works, but I think all should be OK
- (UIImage *)image:(UIImage*)originalImage scaledToSize:(CGSize)size { //avoid redundant drawing if (CGSizeEqualToSize(originalImage.size, size)) { return originalImage; } //create drawing context UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f); //draw [originalImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)]; //capture resultant image UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //return image return image; }
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