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
This is a dumb one, so stupid I'm proud of it. Bottom line is I ended up on this SO post thinking contentMode = UIViewContentModeScaleAspectFit was broken when in fact what was really broken was my expectation of the outcome. I was working with a square image in a square view so Fit and Fill were having the exact same effect. I cried like a baby when I couldn't get it to sit widescreen inside the square.
I just ran it and your code works fine. It could have something to do with you specifying JPG when its actually a png?
You can also use UIViewContentModeScaleAspectFill, but make sure that your bounds are within the view limit because otherwise the outside might be clipped
Setting the size must occur AFTER setting the contentMode
In my case, i solved this removing some constraints that resize the imageview that i set by error.
[UPDATE]
It is "Size Constraints" the one that make size relative to another view.
Xamarin IOS Doc
I had the same problem. In my project a
UIImage
created withimageWithCIImage:
never respected thecontentMode
of theUIImageView
it was inserted into.Some images do also have weird attributes that causes the same problem. Converting it to PNG with Photoshop always worked on them.
Not working with
contentMode
:The
UIImageView
seems to resize based on theCGImage
.You need to render the CIImage to a CGImage and can than use that as an UIImage. This will work with
UIViewContentModeAspectFit
.Use for example
createCGImage:fromRect:
, or better use aCGImage
from the start.