Resize UIImageView in iOS

3.1k views Asked by At

I'm uring iCarossel with SDWebImage. Everything works just fine but when the image size is too big it just goes out of the screen.

Following is the snippet where image view is generated

view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

[((UIImageView *)view) setImageWithURL:[NSURL URLWithString:@"http://www.pizzatower.com/img/icons/Pizza-icon.png"]];
//        [((UIImageView *)view) setImageWithURL:[NSURL URLWithString:@"http://www.rivercitypizza.com/PepperoniPizza-full.jpg"]];

view.contentMode = UIViewContentModeCenter;
view.frame = CGRectMake(0, 0, 256, 256);
label = [[UILabel alloc] initWithFrame:view.bounds];
label.backgroundColor = [UIColor clearColor];
label.font = [label.font fontWithSize:10];
label.tag = 1;
[view addSubview:label];

I tried changint the frame attribute but nothing changes. Could someone point me out how to resize the image and keep it within the size of the screen?

3

There are 3 answers

1
slecorne On BEST ANSWER

If you use view.contentMode = UIViewContentModeScaleAspectFit; your image will be scaled to fit inside the frame.

0
Pradhyuman sinh On
  1. Set Your UIImageView ContentMode

    YourImageView.contentMode=UIViewContentModeScaleToFill;

  2. Use this code

Write this line in your code.

UIImage *ResizeImage=[self resizeImage:YourMainUIImage resizeSize:CGSizeMake(100,100)];

Add add this method in your ViewController

-(UIImage *) resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size
{
    CGFloat actualHeight = orginalImage.size.height;
    CGFloat actualWidth = orginalImage.size.width;

    float oldRatio = actualWidth/actualHeight;
    float newRatio = size.width/size.height;
    if(oldRatio < newRatio)
    {
        oldRatio = size.height/actualHeight;
        actualWidth = oldRatio * actualWidth;
        actualHeight = size.height;
    }
    else
    {
        oldRatio = size.width/actualWidth;
        actualHeight = oldRatio * actualHeight;
        actualWidth = size.width;
    }

    CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [orginalImage drawInRect:rect];
    orginalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return orginalImage;
}
0
Kumar KL On

Try with this :

  UIImage *resizedImage = [self imageWithImage:self.image scaledToSize:CGSizeMake(768, 1024)];

- (UIImage *)imageWithImage:(UIImage *)imagee 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);
    [imagee drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}