ios - SizeToFit on UIImageView not working

偶尔善良 提交于 2020-01-02 06:18:15

问题


I have a UIImageView which loads in images from the documents directory on the ios file system .

The problem is that when I call

[imageView sizeToFit];

It does not work. I think it is because the image hasn't loaded fully at that point and so the sizeToFit part is called before it has the image width & height.

Could someone point me in the direction of a fix please.

Here is my code:

imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.image = [UIImage imageWithContentsOfFile:[FileOperations getLibraryPath:[NSString stringWithFormat:@"%d.png", listData.imageId]]];
[imageView sizeToFit];
[imageScroll setContentOffset:CGPointMake(0, 0)];
imageScroll.contentSize = imageView.frame.size;
imageScroll.decelerationRate = UIScrollViewDecelerationRateFast;
imageScroll.minimumZoomScale = 1;
imageScroll.maximumZoomScale = 2;
[imageScroll setZoomScale:imageScroll.minimumZoomScale];
[imageScroll addSubview:imageView];

Thanks, Ashley


回答1:


Check the image size:

NSLog(@"%@", NSStringFromCGSize(imageView.image.size));

You may want to set imageView frame based on the image size manually, for example, if the image is too large to fit the imageView's superview.




回答2:


UIImageView *myImage = [[UIImageView alloc]init];
myImage.contentMode = UIViewContentModeScaleAspectFit;
myImage.image = [UIImage imageName:@"image.png"];
[self.view addSubview:myImage];



回答3:


sizeToFit should work in your situation, but fails if the UIImage is nil.

UIImage's imageWithContentsOfFile: returns a (completely loaded) reference to a UIImage or nil. Are you sure that you're passing the right path?



来源:https://stackoverflow.com/questions/10452047/ios-sizetofit-on-uiimageview-not-working

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