原文地址
http://blog.csdn.net/u010424349/article/details/9139183
馬上就要開項目了,大哥讓我寫個控件出來,到時候可以直接用。
好了閒話不多說,直接說思路。
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 p_w_picpathNamed:p_w_picpathName];
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;
}
}