uiscrollview 图片放大缩小

1、UIScrollView下图片的捏合放大和缩小,我们直接用scrollView自带的属性就可以了,这个没什么好说,我们直接贴代码:
[plain] view plaincopy
//控制器  
 theScroll=[[UIScrollView alloc] initWithFrame:frame];  
 theScroll.userInteractionEnabled=YES;  
 theScroll.maximumZoomScale=2.0;//最大倍率(默认倍率)  
 theScroll.minimumZoomScale=1.0;//最小倍率(默认倍率)  
 theScroll.decelerationRate=1.0;//减速倍率(默认倍率)  
 theScroll.delegate=self;  
 theScroll.autoresizingMask =UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleHeight;  
 [self addSubview:theScroll];  
   
 //图片  
 UIImage *theImageName=[UIImage imageNamed:imageName];  
 theImage=[[UIImageView alloc] initWithImage:theImageName];  
 theImage.userInteractionEnabled=YES;  
 theImage.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleHeight;  
 //图片默认作为2倍图处理  
 theImage.frame=CGRectMake(0, 0, theImageName.size.width/2, theImageName.size.height/2);  
 [theScroll addSubview:theImage];  
另外,我们还要在scrollView的delegate里面设置一下:
[plain] view plaincopy
#pragma mark -UIScrollView delegate  
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView  
{  
    return theImage;  
}  
2、scrollView对图片的双击放大和缩小
这里我是通过对双击手势(UIGestureRecognizer)和scrollView的setZoomScale方法来实现放大和缩小。
#创建双击手势
[plain] view plaincopy
//双击手势  
UITapGestureRecognizer *doubelGesture=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleGesture:)];  
doubelGesture.numberOfTapsRequired=2;  
[theImage addGestureRecognizer:doubelGesture];  
[doubelGesture release];  
#另外,我们要记录当前的倍率,然后通过判断,是放大还是缩小。当然,还配合捏合的放大和缩小,所以,要在scrollView的delegate里面记录当前倍率,代码:
[plain] view plaincopy
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale  
{  
    currentScale=scale;  
}  

#双击手势的方法
[plain] view plaincopy
#pragma mark -DoubleGesture Action  
-(void)doubleGesture:(UIGestureRecognizer *)sender  
{  
      
    //当前倍数等于最大放大倍数  
    //双击默认为缩小到原图  
    if (currentScale==_maxScale) {  
        currentScale=minScale;  
        [theScroll setZoomScale:currentScale animated:YES];  
        return;  
    }  
    //当前等于最小放大倍数  
    //双击默认为放大到最大倍数  
    if (currentScale==minScale) {  
        currentScale=_maxScale;  
        [theScroll setZoomScale:currentScale animated:YES];  
        return;  
    }  
      
    CGFloat aveScale =minScale+(_maxScale-minScale)/2.0;//中间倍数  
      
    //当前倍数大于平均倍数  
    //双击默认为放大最大倍数  
    if (currentScale>=aveScale) {  
        currentScale=_maxScale;  
        [theScroll setZoomScale:currentScale animated:YES];  
        return;  
    }  
      
    //当前倍数小于平均倍数  
    //双击默认为放大到最小倍数  
    if (currentScale<aveScale) {  
        currentScale=minScale;  
        [theScroll setZoomScale:currentScale animated:YES];  
        return;  
    }  
}  

 

posted @ 2014-08-19 13:38  zengyanzhi  阅读(604)  评论(0编辑  收藏  举报