ios 根據手勢放大或縮小圖片

來源:互聯網
上載者:User
1.在.h檔案中加入一個變數用來記錄當前的scale值, 讓這個ViewController遵循

UIGestureRecognizerDelegate代理.

並在.h中加入下面這個變數

CGFloat lastScale;


2. 在viewDidLoad中加入下面語句

    UIView *holderView = [[UIViewalloc]initWithFrame:CGRectMake(0,0,320, 416)];

    

    UIImageView *showImgView = [[UIImageViewalloc]initWithFrame:CGRectMake(0,0,320, 416)];

    showImgView.image =img;

    showImgView.contentMode =UIViewContentModeScaleAspectFit;

    [holderView addSubview:showImgView];

    [showImgView release];    

    

   UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizeralloc]initWithTarget:selfaction:@selector(scaGesture:)];

    [pinchRecognizersetDelegate:self];

    [holderView addGestureRecognizer:pinchRecognizer];

    [pinchRecognizerrelease];

    

    [self.viewaddSubview:holderView];

    [holderView release];

3.在加入這個手勢的執行方法

-(void)scaGesture:(id)sender {

    [self.viewbringSubviewToFront:[(UIPinchGestureRecognizer*)senderview]];

   //當手指離開螢幕時,將lastscale設定為1.0

   if([(UIPinchGestureRecognizer*)senderstate] == UIGestureRecognizerStateEnded) {

        lastScale = 1.0;

        return;

    }

    

    CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)senderscale]);

   CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)senderview].transform;

    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);

    [[(UIPinchGestureRecognizer*)senderview]setTransform:newTransform];

   lastScale = [(UIPinchGestureRecognizer*)senderscale];

}


4. 加入手勢的代理方法

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 

shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

    return ![gestureRecognizer isKindOfClass:[UIPanGestureRecognizerclass]];

}



5、運行程式,效果如圖:(注意這裡只能是以圖片中心放大的,不能進行移動圖片,若要移動圖片,需要修改其Transform部分代碼)

下面這個圖是從別處找來的, 自己截圖並上傳比較麻煩, 呵呵

注意:請在真機上運行,在模擬器中無法類比Pinch手勢, 按住option和shift鍵在模擬器上也能類比出兩個手指的手勢

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.