1
votes

I am downloading a rather big image and storing it in a UIImage. I then add that UIImage to a UIImageView to display, but the UIImage is just too large, and of thus, it only displays a portion of the image (the upper-left corner of it). I want it to display the entire UIImage, scaling the image down to fit the UIImageView.

I have looked at a lot of different answers, but I can't get any of them working. I have set the scale mode of the UIImageView to both Aspect Fill, fit and you name it (also tried clip subviews) but nothing is working.

Here is the code:

UIImage *trackImg = [UIImage imageWithContentsOfFile:trackImagePath];
_backgroundImage.image = trackImg;

Code is simple, but all it does is download a UIImage, and set it as the image of a UIImageview. The UIImageView is configured in the interface-builder.

Thanks in advance.

2
can you show your code?Huy Nghia
doh sorry, added now.J.B.J.
did you set _backgroundImage.contentMode = UIViewContentModeScaleAspectFit; ? so did you check _backgroundImage frame ?Huy Nghia
Ooh it was because the size of the frame was off. I set the constraints wrong and that messed it up -.-' Still getting used to this new constraint system (find it a little hard sometimes), and i ended up looking in the wrong place. Thanks a lot, and so sorry for this.J.B.J.

2 Answers

2
votes

You can resize your image using the scaleToSize method:

-(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    // Here pass new size you need
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

Pass your UIImage and it should resize. Call the method as:

[self imageWithImage:[UIImage imageNamed:@"yourImage.png"] scaledToSize:CGSizeMake(25,45)];
0
votes

The error was in the size of the imageView (thanks Huy Nghia). I set the constraints wrong, which resulted in the imageView having a different size than i expected, which i couldn't easily detect since i wanted it to fill the entire screen.

If anyone else is having difficulties, try making sure your constraints are right.