1. 程式人生 > >#iOS開發筆記#如何限制UIImageView放大縮小的比例

#iOS開發筆記#如何限制UIImageView放大縮小的比例

當一個UIImageView實現了手勢操作並可以用兩指實現放大縮小之後,如何能限制放大縮小的比例?

來源:

http://stackoverflow.com/a/5446348/2177332

程式碼實現:

@property CGFloat lastScale;
- (void)pinchGestureDetected:(UIPinchGestureRecognizer *)recognizer
{
    
    UIGestureRecognizerState state = [recognizer state];

    if(state == UIGestureRecognizerStateBegan) {
        // Reset the last scale, necessary if there are multiple objects with different scales
        _lastScale = [recognizer scale];
    }
    
    if (state == UIGestureRecognizerStateBegan ||
        state == UIGestureRecognizerStateChanged) {
        
        CGFloat currentScale = [[[recognizer view].layer valueForKeyPath:@"transform.scale"] floatValue];
        
        // Constants to adjust the max/min values of zoom
        const CGFloat kMaxScale = 3.0;
        const CGFloat kMinScale = 1.0;
        
        CGFloat newScale = 1 -  (_lastScale - [recognizer scale]);
        newScale = MIN(newScale, kMaxScale / currentScale);
        newScale = MAX(newScale, kMinScale / currentScale);
        CGAffineTransform transform = CGAffineTransformScale([[recognizer view] transform], newScale, newScale);
        [recognizer view].transform = transform;
        _lastScale = [recognizer scale];  // Store the previous scale factor for the next pinch gesture call

    }
}

注:kMaxScale和kMinScale分別代表最大和最小的縮放比例。