我有一个显示照片的 iOS 应用程序,用户应该能够在其中查看和缩放图像。根据要求,图像应该显示在整个屏幕上(不应显示透明部分,并且图像应填充整个屏幕),因此我自己对 UIImageView
使用了 AspectFill
模式。为了实现缩放功能,使用了 UIScrollView
并实现了 UIScrollView
的 viewForZoomingInScrollView
委托(delegate)方法。 ImageView 连接到 StoryBoard 中 ScrollView 的四个边缘,两个约束(imageHeight 和 imageWidth)连接到 IBOutlet。这些约束将在 ViewControllers viewDidLayoutSubviews
方法中更新。
我添加了以下代码供您引用。
- (void)setImageViewModes {
self.scrollView.minimumZoomScale = CALCULATD_ZOOM_SCALE;
self.pageImageView.contentMode = UIViewContentModeScaleAspectFill;
}
pragma mark - UIScrollView Delegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return MY_IMAGE_VIEW;
}
- (void)updateImageViewConstraints {
self.imageHeight.constant = CGRectGetHeight(self.scrollView.frame);
self.imageWidth.constant = CGRectGetWidth(self.scrollView.frame);
[self.view layoutIfNeeded];
}
但是,当我尝试缩小图像时,它会反弹到其初始状态,并且图像的外部部分被剪裁(它仅显示图像的初始填充部分)。是否有任何解决方法可以在缩小时查看整个图像?
我尝试为 UIScrollView 设置最小缩放比例(我的代码中有一个方法来计算图像的最小缩放比例)并且缩放功能有效。然而,当我们缩小时,UIIMage总是移动到 ScrollView 的左上角(附上屏幕截图供您引用)。
我通过Center content of UIScrollView when smaller找到了这个问题的解决方案(第三个答案)通过子类化 UIScrollView 并在 ScrollView 的“layoutSubviews”方法中调整 ImageView 框架。缩小时效果很好。但是,当我们缩放并滚动图像以查看边缘/侧面部分时, ScrollView 将 ImageView 重新调整到中心,我无法在放大状态下看到图像的侧面部分。此问题的任何解决方法?
最佳答案
使用这个
-(void)scrollViewDidZoom:(UIScrollView *)scrollView1{
[self centerScrollViewContent];
- (void)centerScrollViewContent {
CGSize boundsSize = self.scrollView.bounds.size;
CGRect contentsFrame = self.drawingView.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
self.drawingView.frame = contentsFrame;
关于ios - ScrollView 缩放问题中的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27618384/