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;  
    }  
}  
相關文章
相關標籤/搜索