我有一个自定义的UIViewController,我在其上添加了一个UIImageView(在StoryBoard上),然后将UIImageView嵌入到UIScrollView中。我的程序将图像加载到imageView中并将其缩放到适当的位置。通过适当的配合,我的意思是:
我目前在viewWillAppear中执行此操作。下面是我的方法代码和计算正确zoomScale的辅助方法:
-(float) findZoomScale {
float widthRatio = self.view.bounds.size.width / self.imageView.image.size.width;
float heightRatio = self.view.bounds.size.height / self.imageView.image.size.height;
float ratio;
if (widthRatio > heightRatio) ratio = widthRatio;
else ratio = heightRatio;
return ratio;
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
self.imageView.image = self.image;
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
self.scrollView.contentSize = self.imageView.image.size;
self.scrollView.zoomScale = [self findZoomScale];
[self.scrollView flashScrollIndicators];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:self.photoURL]];
self.imageView.image = self.image;
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width,
self.imageView.image.size.height);
self.scrollView.delegate = self;
self.scrollView.zoomScale = 1.0;
self.navigationItem.title = self.photoTitle;
self.scrollView.autoresizesSubviews = YES;
self.scrollView.autoresizingMask = (UIViewAutoresizingFlexibleBottomMargin |
UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight);
}
此代码可用于初始加载图像,无论iPhone是横向还是纵向。但是当我用已经加载的图像旋转iPhone时,它没有正确地重新缩放。我试图在didRotateFromInterfaceOrientation中进行重新缩放,使用scrollView的zoomScale属性进行重新缩放,但我无法使其工作。这是重新调整的正确位置吗?如果是这样,我该怎么做?感谢。
杜安
答案 0 :(得分:18)
我刚才遇到了这个问题(我假设你也在使用CS193p 4),并在调整旋转后调整UIScrollView的zoomScale
之前将contentSize
设置为1来解决它。
例如:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
//reset zoomScale back to 1 so that contentSize can be modified correctly
self.scrollView.zoomScale = 1;
// reset scrolling area equal to size of image
self.scrollView.contentSize = self.imageView.image.size;
//reset the image frame to the size of the image
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
//set the zoomScale to what we actually want
self.scrollView.zoomScale = [self findZoomScale];
}
答案 1 :(得分:0)
您可以使用
-(void)viewWillLayoutSubviews
在你的UIViewController中。每当加载/旋转/调整视图时,都会调用此方法。