UIImageView image stretched even though contentMod

2019-06-15 10:45发布

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

5条回答
地球回转人心会变
2楼-- · 2019-06-15 11:23

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-15 11:29

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

查看更多
Lonely孤独者°
4楼-- · 2019-06-15 11:35

Setting the size must occur AFTER setting the contentMode

[imageView setContentMode: UIViewContentModeScaleAspectFit];
imageView.frame = CGRectMake(x, y, width, height);
查看更多
乱世女痞
5楼-- · 2019-06-15 11:37

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

查看更多
祖国的老花朵
6楼-- · 2019-06-15 11:39

I had the same problem. In my project a UIImage created with imageWithCIImage: never respected the contentMode of the UIImageView 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:

    CIImage * __strong ciImage = [CIImage imageWithContentsOfURL:url];
    _image = [UIImage imageWithCIImage:ciImage];

The UIImageView seems to resize based on the CGImage.

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 a CGImage from the start.

查看更多
登录 后发表回答