屏幕旋转变换

  • 注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_handleDeviceOrientationChange)
                                                 name:UIDeviceOrientationDidChangeNotification object:nil];
  • 旋转动画
- (void)rotate:(SJOrientation)orientation animated:(BOOL)animated completion:(void (^__nullable)(SJOrentationObserver * _Nonnull))block {
    if ( !_view || !_targetSuperview ) return;
    
    if ( self.isTransitioning ) return;
    
    _transitioning = YES;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    UIInterfaceOrientation ori = UIInterfaceOrientationUnknown;
    
    switch ( orientation ) {
        case SJOrientation_LandscapeRight: {
            ori = UIInterfaceOrientationLandscapeLeft;
            transform = CGAffineTransformMakeRotation(-M_PI_2);
        }
            break;
        case SJOrientation_LandscapeLeft: {
            ori = UIInterfaceOrientationLandscapeRight;
            transform = CGAffineTransformMakeRotation(M_PI_2);
        }
            break;
        case SJOrientation_Portrait: {
            ori = UIInterfaceOrientationPortrait;
            transform = CGAffineTransformIdentity;
            [_blackView removeFromSuperview];
        }
            break;
    }
    
    SJOrientation oldOri = _orientation;
    SJOrientation newOri = orientation;
    
    if ( oldOri == SJOrientation_Portrait ) {
        CGRect frame = [__window convertRect:_view.frame fromView:_targetSuperview];
        _view.frame = frame;
        [__window addSubview:_view];
        _portrait = frame;
    }
    
    
    // update
    _orientation = orientation;
    
    [UIApplication sharedApplication].statusBarOrientation = ori;
    
    [UIView beginAnimations:@"rotation" context:NULL];
    if ( animated ) [UIView setAnimationDuration:_duration];
    else [UIView setAnimationDuration:0];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(_animationDidStop)];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    if ( newOri == SJOrientation_Portrait ) {
        _view.bounds = CGRectMake(0, 0, _portrait.size.width, _portrait.size.height);
        _view.center = CGPointMake(_portrait.origin.x + _portrait.size.width * 0.5, _portrait.origin.y + _portrait.size.height * 0.5);
    }
    else {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        CGFloat height = [UIScreen mainScreen].bounds.size.height;
        CGFloat max = MAX(width, height);
        CGFloat min = MIN(width, height);
        _view.bounds = CGRectMake(0, 0, max, min);
        _view.center = CGPointMake(min * 0.5, max * 0.5);
    }
    [_view setTransform:transform];
    [UIView commitAnimations];
}

你可能感兴趣的:(屏幕旋转变换)