首页 > 代码库 > ScrollView双击图片定点放大

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具体干了什么事情,这就要让喜欢刨根问底的童鞋用一些力气了,然后@给我哦。

ScrollView双击图片定点放大