缩放后 UIImageView 在 PageControl 的右侧被切断
Posted
技术标签:
【中文标题】缩放后 UIImageView 在 PageControl 的右侧被切断【英文标题】:UIImageView is cut off on right side within PageControl after zooming 【发布时间】:2013-05-09 18:48:24 【问题描述】:放大后我的图像在右侧被切断。如果我没有使用 cgrect make 设置偏移量,那么它不会被切断,但我希望我的图像在屏幕上居中。缩放后如何使图像居中而不切断正确的部分?
- (void)viewDidLoad
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor grayColor];
UIScrollView *mainScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
mainScrollView.pagingEnabled = YES;
mainScrollView.showsHorizontalScrollIndicator = NO;
mainScrollView.showsVerticalScrollIndicator = NO;
CGRect innerScrollFrame = mainScrollView.bounds;
for (NSInteger i = 0; i < 2; i++)
UIImageView *imageForZooming = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"page%d", i + 1]]];
imageForZooming.tag = VIEW_FOR_ZOOM_TAG;
imageForZooming.frame = CGRectMake(50, 0, imageForZooming.bounds.size.width, imageForZooming.bounds.size.height);
UIScrollView *pageScrollView = [[UIScrollView alloc] initWithFrame:innerScrollFrame];
pageScrollView.minimumZoomScale = 0.5f;
pageScrollView.maximumZoomScale = 1.0f;
pageScrollView.contentSize = imageForZooming.bounds.size;
pageScrollView.delegate = self;
[pageScrollView addSubview:imageForZooming];
[mainScrollView addSubview:pageScrollView];
if (i < 1)
innerScrollFrame.origin.x += innerScrollFrame.size.width;
pageScrollView.zoomScale = 0.5f;
mainScrollView.contentSize = CGSizeMake(innerScrollFrame.origin.x + innerScrollFrame.size.width, mainScrollView.bounds.size.height);
[self.view addSubview:mainScrollView];
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
return [scrollView viewWithTag:VIEW_FOR_ZOOM_TAG];
编辑:这是我的视图层次结构
查看 主滚动视图 innerScrollFrame pageScrollView imageForZooming innerScrollFrame pageScrollView imageForZooming【问题讨论】:
【参考方案1】:对于以后遇到同样问题的其他人,我所做的是添加以下 UIScrollViewDelegate 协议:
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
UIView *subView = [scrollView.subviews objectAtIndex:0];
CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width) ? (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height) ? (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
subView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
scrollView.contentSize.height * 0.5 + offsetY);
我在这里找到了答案:Center content of UIScrollView when smaller
以便图像在缩放后居中,而不是应用最初应用的偏移量。像魅力一样工作。现在,当我缩放时,我的图像在任一页面控件上都不会被截断,并且我可以在视图的开头将图像居中。
【讨论】:
以上是关于缩放后 UIImageView 在 PageControl 的右侧被切断的主要内容,如果未能解决你的问题,请参考以下文章
如何以编程方式将 UIImageView 缩放到固定宽度和灵活高度?