UIImageView image stretched even though contentMode = UIViewContentModeScaleAspectFit

大憨熊 提交于 2019-12-10 12:33:32

问题


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


回答1:


Setting the size must occur AFTER setting the contentMode

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



回答2:


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.




回答3:


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




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/14485975/uiimageview-image-stretched-even-though-contentmode-uiviewcontentmodescaleaspe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!