今天的重點:利用ScrollView進行圖片的縮放
直接先說原理吧--原理:利用了scrollview的回調函數(如下)以及scrollview自己內部的一些縮放規則(其實我也還沒弄清楚具體scrollview干了什麼事),只是知道了它可以怎麼做-_-#
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
returnself.zoomImageView;
}
其實今天的縮放部分我還加上了常見的 雙擊圖片的縮小與放大,先上代碼:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//自身屬性的一些設置
NSLog(@"%@",NSStringFromCGRect(frame));
self.delegate =self;
self.showsVerticalScrollIndicator =NO;
self.showsHorizontalScrollIndicator =NO;
self.maximumZoomScale =3;
//承載當前圖片的imageview
self.zoomImageView = [[[UIImageViewalloc] init] autorelease];
self.zoomImageView.userInteractionEnabled =YES;
self.zoomImageView.frame =CGRectMake(0.0f, 0.0f, frame.size.width , frame.size.height);
self.zoomImageView.image = [UIImageimageNamed:@"lichengwu.jpeg"];
[self addSubview:self.zoomImageView];
// Add gesture,double tap zoom imageView.
UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizeralloc] initWithTarget:self
action:@selector(handleDoubleTap:)];
[doubleTapGesture setNumberOfTapsRequired:2];
[ self.zoomImageViewaddGestureRecognizer:doubleTapGesture];
[doubleTapGesture release];
// initialize tapclicks
tapClicks = NO;
}
return self;
}
接著上代碼:
#pragma mark - Zoom methods
- (void)handleDoubleTap:(UIGestureRecognizer *)gesture
{
float newScale;
if (!tapClicks) {
newScale = self.zoomScale *2.0;
}
else{
newScale = self.zoomScale *0.0;
}
CGRect zoomRect = [selfzoomRectForScale:newScale withCenter:[gesturelocationInView:gesture.view]];
[self zoomToRect:zoomRectanimated:YES];
tapClicks = !tapClicks;
}
這一部分也是相當的一目了然,就是處理雙擊事件函數,是縮小還是放大,正正的處理圖片的函數如下:
#pragma mark - CommonMethods
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
CGRect zoomRect;
zoomRect.size.height =self.frame.size.height / scale;
zoomRect.size.width =self.frame.size.width / scale;
zoomRect.origin.x = center.x - (zoomRect.size.width /2.0);
zoomRect.origin.y = center.y - (zoomRect.size.height /2.0);
return zoomRect;
}
看見原理了沒,其實就是獲得當前點擊處的中心X與原來圖片尺寸的差值,然後傳遞給Scrollview進行縮放,至於scrollview具體干了什麼事情,這就要讓喜歡刨根問底的童鞋用一些力氣了,然後@給我哦。