在UIScrollView中缩放UIImageView超出范围

时间:2013-03-22 12:23:56

标签: iphone ios objective-c cocoa-touch uiscrollview

我已成功实现了UIImageViewUIScrollView的缩放,但我遇到了一个令我恼火的奇怪问题。

基本上,当我放大图像时

enter image description here

我可以平移视图以实际滚动出图像边框,我留下了这样的黑色区域: enter image description here

随着我放大更多,我可以让黑色边框填满整个屏幕! 同时在iPhone Photo应用程序中,您无法缩小实际图像。我的实施中有什么问题?

看起来像这样:

UIImage *imageToDisplay = [UIImage imageWithData:tmpImageData];
imageViewMain.image = imageToDisplay;
imageViewMain.frame = CGRectMake(0, 0, scrollViewMain.frame.size.width, scrollViewMain.frame.size.height);
imageViewMain.contentMode = UIViewContentModeScaleAspectFit;

scrollViewMain.delegate = self;
scrollViewMain.minimumZoomScale = 1.0;
scrollViewMain.maximumZoomScale = 9.0;
scrollViewMain.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
scrollViewMain.contentSize = imageViewMain.frame.size;

[self.view addSubview:scrollViewMain];
[scrollViewMain addSubview:imageViewMain];

我也实现了这个方法:

- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageViewMain;
}

提前致谢!

编辑: 当我第一次加载视图时,我收缩了我的UIImageView以适应滚动视图,图像看起来像这样:

enter image description here

2 个答案:

答案 0 :(得分:2)

试试这段代码....在需要的地方更改一些代码...对UIPinchGestureRecognizer使用UIImageView,然后在UIScrollView中添加此图片,如下所示.. < / p>

UIImageView *img = [[UIImageView alloc]init];
img.image = [UIImage imageWithData:tmpImageData];
img.userInteractionEnabled = YES;
img.frame = CGRectMake(210,100, 200, 200);/// define frame which you want...
[img sizeToFit];

UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scale:)];
[pinchRecognizer setDelegate:self];
[img addGestureRecognizer:pinchRecognizer];
[pinchRecognizer release];
[scrollViewMain addSubview:img];
[scrollViewMain bringSubviewToFront:img];
[img release]; 

然后将此下方代码粘贴到.m文件中......

#pragma mark GestureRecognizer Methods
-(void)scale:(id)sender 
{
    UIView *imgTempGest = [sender view];
    if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) 
    {
        lastScale = 1.0;
        return;
    }
    CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);

    CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);

    [[(UIPinchGestureRecognizer*)sender view] setTransform:newTransform];

    [imgTempGest setTransform:newTransform];

    lastScale = [(UIPinchGestureRecognizer*)sender scale];
}

这里对于LastScale,只需在.h文件中定义该变量,如下文...

CGFloat lastScale;

我希望这对你有帮助......

答案 1 :(得分:1)

原始图片是否包含顶部和底部的边框?如果实际图像包含黑色顶部和底部黑色区域,则可以在那里使用相同的代码,输出没有错误。并添加此代码,

  

scrollView.scrollEnabled = YES

也改变了,

  

scrollView.contentSize = imageView.bounds.size;

此外,您提供的缩放比例为9.您还需要多少?将其更改为3或4并尝试。您的问题将得到解决