UIImageView image stretched even though contentMode = UIViewContentModeScaleAspectFit

Mike picture Mike · Jan 23, 2013 · Viewed 11.9k times · Source

I am really disappointed by the way UIImageView displays the image.

I have following piece of code:

UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 100)];
imgview.image = [UIImage imageNamed:@"img.JPG"];
imgview.backgroundColor = [UIColor greenColor];
imgview.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:imgview];

What I get is a following screenshot:

http://img26.imageshack.us/img26/3686/screenshot20130123at629.png

[image is stretched to full width of UIImageView and does not even take full height]

Original image:

http://img248.imageshack.us/img248/341/screenshot20130123at638.png

Answer

Jonathan picture Jonathan · Sep 16, 2013

Setting the size must occur AFTER setting the contentMode

[imageView setContentMode: UIViewContentModeScaleAspectFit];
imageView.frame = CGRectMake(x, y, width, height);