Подтвердить что ты не робот

Как мне сделать переход между iOS на просмотр/переход?

Я пытаюсь сделать переходную анимацию в iOS, где контроллер представлений или представлений расширяется, чтобы заполнить весь экран, а затем завершайте его прежнее положение. Я не уверен, что этот тип перехода официально называется, но вы можете увидеть пример в приложении YouTube для iPad. Когда вы нажимаете один из миниатюр результатов поиска в сетке, он расширяется из миниатюры, а затем возвращается обратно в миниатюру, когда вы возвращаетесь к поиску.

Мне интересны два аспекта этого:

  • Как вы это сделаете при переходе между одним видом и другим? Другими словами, если вид A занимает некоторую область экрана, как бы вы переместили его для просмотра B, который занимает весь экран, и наоборот?

  • Как бы вы перешли к модальному виду таким образом? Другими словами, если UIViewController C в настоящее время отображает и содержит представление D, которое занимает часть экрана, как вы выглядите так, как будто вид D превращается в UIViewController E, который представлен в модуле поверх C?

Изменить: Я добавляю щедрость, чтобы узнать, вызывает ли этот вопрос больше любви.

Изменить: У меня есть исходный код, который делает это, и идея Аномии работает как прелесть, с некоторыми уточнениями. Сначала я попробовал оживить вид модального контроллера (E), но он не вызывал эффекта ощущения, будто вы приближаетесь к экрану, потому что в (C) он не расширял все элементы вокруг эскизов. Итак, я попробовал анимировать исходный вид контроллера (C), но его перерисовка сделана для резкой анимации, и такие вещи, как фоновые текстуры, не масштабировались должным образом. Итак, что я сделал, это изображение исходного контроллера (C) и масштабирование внутри модального представления (E). Этот метод существенно более сложный, чем мой оригинальный, но он выглядит красиво! Я думаю, что iOS должен делать свои внутренние переходы. Во всяком случае, вот код, который я написал как категория на UIViewController.

UIViewController + Transitions.h:

#import <Foundation/Foundation.h>

@interface UIViewController (Transitions)

// make a transition that looks like a modal view 
//  is expanding from a subview
- (void)expandView:(UIView *)sourceView 
        toModalViewController:(UIViewController *)modalViewController;

// make a transition that looks like the current modal view 
//  is shrinking into a subview
- (void)dismissModalViewControllerToView:(UIView *)view;

@end

UIViewController + Transitions.m:

#import "UIViewController+Transitions.h"

@implementation UIViewController (Transitions)

// capture a screen-sized image of the receiver
- (UIImageView *)imageViewFromScreen {
  // make a bitmap copy of the screen
  UIGraphicsBeginImageContextWithOptions(
    [UIScreen mainScreen].bounds.size, YES, 
    [UIScreen mainScreen].scale);
  // get the root layer
  CALayer *layer = self.view.layer;
  while(layer.superlayer) {
    layer = layer.superlayer;
  }
  // render it into the bitmap
  [layer renderInContext:UIGraphicsGetCurrentContext()];
  // get the image
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  // close the context
  UIGraphicsEndImageContext();
  // make a view for the image
  UIImageView *imageView = 
    [[[UIImageView alloc] initWithImage:image]
      autorelease];

  return(imageView);
}

// make a transform that causes the given subview to fill the screen
//  (when applied to an image of the screen)
- (CATransform3D)transformToFillScreenWithSubview:(UIView *)sourceView {
  // get the root view
  UIView *rootView = sourceView;
  while (rootView.superview) rootView = rootView.superview;
  // convert the source view center and size into the coordinate
  //  system of the root view
  CGRect sourceRect = [sourceView convertRect:sourceView.bounds toView:rootView];
  CGPoint sourceCenter = CGPointMake(
    CGRectGetMidX(sourceRect), CGRectGetMidY(sourceRect));
  CGSize sourceSize = sourceRect.size;
  // get the size and position we're expanding it to
  CGRect screenBounds = [UIScreen mainScreen].bounds;
  CGPoint targetCenter = CGPointMake(
    CGRectGetMidX(screenBounds),
    CGRectGetMidY(screenBounds));
  CGSize targetSize = screenBounds.size;
  // scale so that the view fills the screen
  CATransform3D t = CATransform3DIdentity;
  CGFloat sourceAspect = sourceSize.width / sourceSize.height;
  CGFloat targetAspect = targetSize.width / targetSize.height;
  CGFloat scale = 1.0;
  if (sourceAspect > targetAspect)
    scale = targetSize.width / sourceSize.width;
  else
    scale = targetSize.height / sourceSize.height;
  t = CATransform3DScale(t, scale, scale, 1.0);
  // compensate for the status bar in the screen image
  CGFloat statusBarAdjustment =
    (([UIApplication sharedApplication].statusBarFrame.size.height / 2.0) 
      / scale);
  // transform to center the view
  t = CATransform3DTranslate(t, 
    (targetCenter.x - sourceCenter.x), 
    (targetCenter.y - sourceCenter.y) + statusBarAdjustment, 
    0.0);

  return(t);
}

- (void)expandView:(UIView *)sourceView 
        toModalViewController:(UIViewController *)modalViewController {

  // get an image of the screen
  UIImageView *imageView = [self imageViewFromScreen];

  // insert it into the modal view hierarchy
  [self presentModalViewController:modalViewController animated:NO];
  UIView *rootView = modalViewController.view;
  while (rootView.superview) rootView = rootView.superview;
  [rootView addSubview:imageView];

  // make a transform that makes the source view fill the screen
  CATransform3D t = [self transformToFillScreenWithSubview:sourceView];

  // animate the transform
  [UIView animateWithDuration:0.4
    animations:^(void) {
      imageView.layer.transform = t;
    } completion:^(BOOL finished) {
      [imageView removeFromSuperview];
    }];
}

- (void)dismissModalViewControllerToView:(UIView *)view {

  // take a snapshot of the current screen
  UIImageView *imageView = [self imageViewFromScreen];

  // insert it into the root view
  UIView *rootView = self.view;
  while (rootView.superview) rootView = rootView.superview;
  [rootView addSubview:imageView];

  // make the subview initially fill the screen
  imageView.layer.transform = [self transformToFillScreenWithSubview:view];
  // remove the modal view
  [self dismissModalViewControllerAnimated:NO];

  // animate the screen shrinking back to normal
  [UIView animateWithDuration:0.4 
    animations:^(void) {
      imageView.layer.transform = CATransform3DIdentity;
    }
    completion:^(BOOL finished) {
      [imageView removeFromSuperview];
    }];
}

@end

Вы можете использовать его в подклассе UIViewController:

#import "UIViewController+Transitions.h"

...

- (void)userDidTapThumbnail {

  DetailViewController *detail = 
    [[DetailViewController alloc]
      initWithNibName:nil bundle:nil];

  [self expandView:thumbnailView toModalViewController:detail];

  [detail release];
}

- (void)dismissModalViewControllerAnimated:(BOOL)animated {
  if (([self.modalViewController isKindOfClass:[DetailViewController class]]) &&
      (animated)) {

    [self dismissModalViewControllerToView:thumbnailView];

  }
  else {
    [super dismissModalViewControllerAnimated:animated];
  }
}

Изменить: Ну, оказывается, что на самом деле не обрабатываются ориентации интерфейса, отличные от портрета. Поэтому мне пришлось переключиться на анимацию перехода в UIWindow, используя контроллер вида для прохождения по вращению. См. Гораздо более сложную версию ниже:

UIViewController + Transitions.m:

@interface ContainerViewController : UIViewController { }
@end

@implementation ContainerViewController
  - (BOOL)shouldAutorotateToInterfaceOrientation:
          (UIInterfaceOrientation)toInterfaceOrientation {
    return(YES);
  }
@end

...

// get the screen size, compensating for orientation
- (CGSize)screenSize {
  // get the size of the screen (swapping dimensions for other orientations)
  CGSize size = [UIScreen mainScreen].bounds.size;
  if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
    CGFloat width = size.width;
    size.width = size.height;
    size.height = width;
  }
  return(size);
}

// capture a screen-sized image of the receiver
- (UIImageView *)imageViewFromScreen {

  // get the root layer
  CALayer *layer = self.view.layer;
  while(layer.superlayer) {
    layer = layer.superlayer;
  }
  // get the size of the bitmap
  CGSize size = [self screenSize];
  // make a bitmap to copy the screen into
  UIGraphicsBeginImageContextWithOptions(
    size, YES, 
    [UIScreen mainScreen].scale);
  CGContextRef context = UIGraphicsGetCurrentContext();
  // compensate for orientation
  if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
    CGContextTranslateCTM(context, size.width, 0);
    CGContextRotateCTM(context, M_PI_2);
  }
  else if (self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
    CGContextTranslateCTM(context, 0, size.height);
    CGContextRotateCTM(context, - M_PI_2);
  }
  else if (self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
    CGContextTranslateCTM(context, size.width, size.height);
    CGContextRotateCTM(context, M_PI);
  }
  // render the layer into the bitmap
  [layer renderInContext:context];
  // get the image
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  // close the context
  UIGraphicsEndImageContext();
  // make a view for the image
  UIImageView *imageView = 
    [[[UIImageView alloc] initWithImage:image]
      autorelease];
  // done
  return(imageView);
}

// make a transform that causes the given subview to fill the screen
//  (when applied to an image of the screen)
- (CATransform3D)transformToFillScreenWithSubview:(UIView *)sourceView
                 includeStatusBar:(BOOL)includeStatusBar {
  // get the root view
  UIView *rootView = sourceView;
  while (rootView.superview) rootView = rootView.superview;
  // by default, zoom from the view bounds
  CGRect sourceRect = sourceView.bounds;
  // convert the source view center and size into the coordinate
  //  system of the root view
  sourceRect = [sourceView convertRect:sourceRect toView:rootView];
  CGPoint sourceCenter = CGPointMake(
    CGRectGetMidX(sourceRect), CGRectGetMidY(sourceRect));
  CGSize sourceSize = sourceRect.size;
  // get the size and position we're expanding it to
  CGSize targetSize = [self screenSize];
  CGPoint targetCenter = CGPointMake(
    targetSize.width / 2.0,
    targetSize.height / 2.0);

  // scale so that the view fills the screen
  CATransform3D t = CATransform3DIdentity;
  CGFloat sourceAspect = sourceSize.width / sourceSize.height;
  CGFloat targetAspect = targetSize.width / targetSize.height;
  CGFloat scale = 1.0;
  if (sourceAspect > targetAspect)
    scale = targetSize.width / sourceSize.width;
  else
    scale = targetSize.height / sourceSize.height;
  t = CATransform3DScale(t, scale, scale, 1.0);
  // compensate for the status bar in the screen image
  CGFloat statusBarAdjustment = includeStatusBar ?
    (([UIApplication sharedApplication].statusBarFrame.size.height / 2.0) 
      / scale) : 0.0;
  // transform to center the view
  t = CATransform3DTranslate(t, 
    (targetCenter.x - sourceCenter.x), 
    (targetCenter.y - sourceCenter.y) + statusBarAdjustment, 
    0.0);

  return(t);
}

- (void)expandView:(UIView *)sourceView 
        toModalViewController:(UIViewController *)modalViewController {

  // get an image of the screen
  UIImageView *imageView = [self imageViewFromScreen];
  // show the modal view
  [self presentModalViewController:modalViewController animated:NO];
  // make a window to display the transition on top of everything else
  UIWindow *window = 
    [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  window.hidden = NO;
  window.backgroundColor = [UIColor blackColor];
  // make a view controller to display the image in
  ContainerViewController *vc = [[ContainerViewController alloc] init];
  vc.wantsFullScreenLayout = YES;
  // show the window
  [window setRootViewController:vc];
  [window makeKeyAndVisible];
  // add the image to the window
  [vc.view addSubview:imageView];

  // make a transform that makes the source view fill the screen
  CATransform3D t = [self 
    transformToFillScreenWithSubview:sourceView
    includeStatusBar:(! modalViewController.wantsFullScreenLayout)];

  // animate the transform
  [UIView animateWithDuration:0.4
    animations:^(void) {
      imageView.layer.transform = t;
    } completion:^(BOOL finished) {
      // we're going to crossfade, so change the background to clear
      window.backgroundColor = [UIColor clearColor];
      // do a little crossfade
      [UIView animateWithDuration:0.25 
        animations:^(void) {
          imageView.alpha = 0.0;
        }
        completion:^(BOOL finished) {
          window.hidden = YES;
          [window release];
          [vc release];
        }];
    }];
}

- (void)dismissModalViewControllerToView:(UIView *)view {

  // temporarily remove the modal dialog so we can get an accurate screenshot 
  //  with orientation applied
  UIViewController *modalViewController = [self.modalViewController retain];
  [self dismissModalViewControllerAnimated:NO];

  // capture the screen
  UIImageView *imageView = [self imageViewFromScreen];
  // put the modal view controller back
  [self presentModalViewController:modalViewController animated:NO];
  [modalViewController release];

  // make a window to display the transition on top of everything else
  UIWindow *window = 
    [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  window.hidden = NO;
  window.backgroundColor = [UIColor clearColor];
  // make a view controller to display the image in
  ContainerViewController *vc = [[ContainerViewController alloc] init];
  vc.wantsFullScreenLayout = YES;
  // show the window
  [window setRootViewController:vc];
  [window makeKeyAndVisible];
  // add the image to the window
  [vc.view addSubview:imageView];

  // make the subview initially fill the screen
  imageView.layer.transform = [self 
    transformToFillScreenWithSubview:view
    includeStatusBar:(! self.modalViewController.wantsFullScreenLayout)];

  // animate a little crossfade
  imageView.alpha = 0.0;
  [UIView animateWithDuration:0.15 
    animations:^(void) {
      imageView.alpha = 1.0;
    }
    completion:^(BOOL finished) {
      // remove the modal view
      [self dismissModalViewControllerAnimated:NO];
      // set the background so the real screen won't show through
      window.backgroundColor = [UIColor blackColor];
      // animate the screen shrinking back to normal
      [UIView animateWithDuration:0.4 
        animations:^(void) {
          imageView.layer.transform = CATransform3DIdentity;
        }
        completion:^(BOOL finished) {
          // hide the transition stuff
          window.hidden = YES;
          [window release];
          [vc release];
        }];
    }];

}

Уф! Но теперь он выглядит примерно так же, как версия Apple, без использования каких-либо ограниченных API. Кроме того, он работает, даже если ориентация меняется, когда модальный вид спереди.

4b9b3361

Ответ 1

  • Эффект прост. Вы берете полноразмерный вид, инициализируете его transform и center, чтобы расположить его поверх миниатюры, добавить в соответствующий супервизор, а затем в блок анимации reset transform и center для размещения его в конечной позиции. Чтобы отклонить представление, просто сделайте обратное: в блоке анимации установите transform и center, чтобы расположить его поверх миниатюры, а затем полностью удалите его в блоке завершения.

    Обратите внимание, что попытка увеличить масштаб от точки (т.е. прямоугольника с шириной 0 и 0) приведет к зависанию. Если вы хотите сделать это, увеличьте прямоугольник с шириной и высотой примерно на 0,00001.

  • Один из способов - сделать то же самое, что и в # 1, а затем вызвать presentModalViewController:animated: с анимированным NO, чтобы представить фактический контроллер представления, когда анимация завершена (что, если сделано правильно, приведет к видимая разница из-за вызова presentModalViewController:animated:). И dismissModalViewControllerAnimated: с NO, за которым следует то же, что и в # 1, чтобы отклонить.

    Или вы можете манипулировать видом контроллера модального представления непосредственно, как в # 1, и принять, что parentViewController, interfaceOrientation, а некоторые другие вещи просто не будут работать правильно в модульном контроллере просмотра, так как Apple не поддерживает мы создаем наши собственные контроллеры контейнеров.

Ответ 2

После просмотра анимации iPad Youtube я понял, что это просто иллюзия. Скажем, что для результатов поиска есть SearchViewController, а DetailViewController для самого видео и дополнительная информация о видео.

DetailViewController имеет такой метод, как - (id)initWithFullscreen, который запускает контроллер просмотра, используя полноэкранное пространство с видео.

Итак, последовательность выглядит следующим образом:

  • SearchViewController представляет свои результаты.
  • Пользователь нажимает на видео.
  • DetailViewController создается с помощью initWithFullscreen, но не отображается
  • Начинается анимация "Масштаб". (Обратите внимание, что мы все еще находимся в SearchViewController, и эта анимация - просто простая анимация View).
  • Окончание анимации "Увеличить" представляет DetailViewController с помощью animated:NO (как упоминалось в Anomie).
  • Теперь отображается DetailViewController и используется полный пробел.

Не похоже, что приложение youtube делает что-то более привлекательное, раздача заключалась в том, что анимация "Zoom in" приближается к черному квадрату, прежде чем представить полное видео.