- Анимации в Android по полочкам (Часть 3. «Низкоуровневые» анимации)
- Часть 3. «Низкоуровневые» анимации
- 1. Рисование на канвасе View
- 2. Рисование на канвасе SurfaceView
- 3. OpenGL
- 19 Best Android Animation UI/UX Libraries
- 1. AndroidViewAnimations
- 2. ListViewAnimations
- 3. AndroidImageSlider
- 4. Transition Everywhere
- 5. Android Ripple Background
- 6. Aphid FlipView
- 7. FragmentTransactionExtended
- 8. KenBurnsView
- 9. Reachability
- 10. AnimationEasingFunctions
- 11. EasyAndroidAnimarions
- 12. InterfaceInteraction
- 13. ViewRevealAnimator
- 14. ArcAnimator
- 15. SearchMenuAnim
- 16. Cross View
- 17. WoWoViewPager
- 18. Lottie
- 19. FerrisWheelView
- To sum up
- Анимации в Android по полочкам (Часть 2. Комплексные анимации)
- Часть 2. Комплексные анимации
- 1. Анимация изменений лэйаута (aka animateLayoutChanges)
- 2. Transitions framework
Анимации в Android по полочкам (Часть 3. «Низкоуровневые» анимации)
Все методы рассмотренные в предыдущих частях хороши и удобны, однако если нам нужно анимировать большое количество объектов, они могут оказаться не подходящими. В данной части мы рассмотрим способы которые нам позволят работать с действительно большим количеством объектов и создавать программно сложные анимации.
Часть 3. «Низкоуровневые» анимации
1. Рисование на канвасе View
Первый способ который мы рассмотрим это рисование в методе onDraw нашего объекта View . Реализуется данный способ просто, достаточно переопределить onDraw и в конце вызвать postInvalidateOnAnimation() .
В данном примере наш drawable будет перемещаться по оси x.
Пример со снежинками выше будет занимать несколько больше кода, т.к. нам нужно хранить состояние каждой отдельной снежинки отдельно.
- Случаи в которых легче нарисовать анимацию программно
Достоинства:
- Можно создавать анимации зависящие абсолютно от любых параметров
- Нет лишних затрат на объекты View
Недостатки:
- Расчёты анимации и отрисовка происходят в UI thread
2. Рисование на канвасе SurfaceView
Что если расчёт следующего шага анимации будет занимать значительное время? Мы всё ещё можем воспользоваться первым способом и вынести расчёты в отдельный поток. Но это всё равно не приведёт к 100% плавности в анимации т.к. UI thread может быть загружен ещё чем либо помимо нашей анимации.
Android позволяет отвязаться от основного цикла(main loop) отрисовки с помощью компонента SurfaceView . А раз мы больше не привязаны к основному циклу, то нам придётся держать свой поток для расчётов и отрисовки. SurfaceView предоставляет коллбэки в которых мы можем запустить и остановить наш поток. В потоке по окончанию расчётов мы будем отрисовывать нашу анимацию.
Реализация той же анимации снежинок будет выглядеть следующим образом:
- Случаи в которых легче нарисовать анимацию программно
- Игры
Достоинства:
- Можно создавать анимации зависящие абсолютно от любых параметров
- Нет лишних затрат на объекты View
Недостатки:
3. OpenGL
Точно также, как и на канвасе, мы можем рисовать используя OpenGL API. Если вы задумали что-либо сложнее чем куб на картинке, то стоит посмотреть в сторону какого-либо движка, например libgdx. К сожалению, даже базовый пример займёт здесь довольно много места, поэтому ограничимся только этим кратким превью.
- Высокая производительность и управление памятью, шейдеры
Недостатки:
Источник
19 Best Android Animation UI/UX Libraries
Mobile applications are getting less static. Interface animations are becoming an integral part of modern apps, making them more user-friendly and navigation through them simpler.
Android projects could use animations for several purposes, specifically to:
- display application status, since the user would be pleased to receive a response to actions he/she triggers. Besides, an appropriate animation would brighten up the user’s expectation when the page content is updated;
- connect various phases of a multiphase process, thereby allowing for a smooth transition between the steps and seamless interaction with the user;
- embed new elements, fitting them harmoniously into the content;
- simplify the interaction process, informing the user what he/she is going through at the moment.
Animations serve to reinforce the user’s action. Nevertheless, rather fanciful or complex effects distract and confuse him/her. As a result, developers should always maintain the golden medium.
Thus, the more you know about animation UI/UX libraries for the Android platform, the easier it is for you to apply them in a smart way. So, shall we start?
1. AndroidViewAnimations
We will begin with AndroidViewAnimations. It is a simple Android library that enables you to create view shake animations. Its developer was inspired by an iOS library, since Android had no analogue at that time. The library allows you to implement a wide variety of animations, including:
Moreover, each item has its own subsections with different effects.
2. ListViewAnimations
ListViewAnimations is another open source library that enables developers to create ListViews with animations. It has the following features:
- appearance animations for items in ListViews, GridViews, other AbsListViews;
- built-in animations include Alpha, SwingRightIn, SwingLeftIn, SwingBottomIn, SwingRightIn and ScaleIn;
- other animations can easily be added;
- supports StickyListHeaders; besides, you can add other implementations without any difficulties;
- Swipe-to-Dismiss, Swipe-To-Dismiss with contextual undo;
- Drag-and-Drop reordering;
- an animated process of adding items;
- you are able to smoothly expand your items to reveal more content.
3. AndroidImageSlider
AndroidImageSlider is an excellent example of an attractive, easy-to-use open source slideshow library. We believe it’s one of the most convenient image sliders on the Android platform.
With its help, you can easily upload your own images from an internet URL, drawable, or file and animate the slideshow with a range of different effects.
4. Transition Everywhere
Transition Everywhere is a backport of Transitions API for Android 4.0 and above. It allows you to change duration, interpolator and start delay for animators inside Transition. It has several transition types:
- Slide;
- Explode and Propagation;
- ChangeImageTransfor;
- Path motion;
- TransitionName;
- Scale;
- Rotate.
The library can come in handy when you are going to animate changes to view position and size, extend Visibility class and perform fade in and fade out animations, or put the animations in sequential order.
5. Android Ripple Background
Android Ripple Background enables creating various ripple animation for your Android app. You can change their color, speed of the wave, and the number of ripples. It will be useful if you are going to animate a button click response or an incoming phone call, etc.
6. Aphid FlipView
Aphid FlipView is a UI component to accomplish the flipping animation similar to Flipboard. It supports:
- flipping horizontally;
- an event listener to get notified when flipping finishes;
- content reloading when flipping;
- different bitmap format for animation, which can be used to reduce peak memory consumption.
7. FragmentTransactionExtended
FragmentTransactionExtended is a library equipped with a set of custom animations between fragments. Compared to FragmentTransaction, which accepts only simple animations, it got its list extended with more complex effects of the following animations:
8. KenBurnsView
KenBurnsView is a library that provides an extension to ImageView, which, in turn, creates an immersive experience by animating its drawable with the help of the Ken Burns Effect.
Advantages of the library are:
- you can change the duration and the interpolator of transitions and pause/resume them.
- you can define how the rectangles to be zoomed and panned will be generated;
- it seamlessly works out of the box with your favorite image loader library;
- you can start using it right away.
9. Reachability
Reachability is a library that enables easy accessing the top of the mobile phone screen. Animations implemented in iPhone 6 and iPhone 6 Plus inspired its developer. Here you can move either the screen or the hover.
10. AnimationEasingFunctions
AnimationEasingFunctions library was created based on AndroidViewAnimation with the help of Easing Functions. It is also aimed at facilitating the process of animation and making animations more real. You can implement it as a grade or just like a glider.
11. EasyAndroidAnimarions
EasyAndroidAnimations is another Android library that makes animation easier. It has above 50 built-in animations that will help you to implement many effects in your app with only several lines of code. You can include the library directly in your Gradle project.
12. InterfaceInteraction
InterfaceInteraction development was bolstered by the PhysicsLayout project. The library captures any interface (screen or view) and throws its UI elements over under the influence of gravity. As a result, one can move them from sideways obliquely. The gravity effect relies on the device’s accelerometer data. The stop method returns all UI elements back in place.
Another feature is a shake animation for UI elements.
The effects can easily be used to decorate any application.
13. ViewRevealAnimator
ViewRevealAnimator view with a lollipop style reveals effect. It enables you to create a smooth animated transition between items.
14. ArcAnimator
ArcAnimator is a library that helps create arc transition animation for Android 2.3. and above.
15. SearchMenuAnim
SearchMenuAnim allows creating a clear and effortless transition from a search icon to a search field.
16. Cross View
Cross View animates across in your app. The library enables you to define color and set a state directly. You can also set an animation duration in milliseconds.
17. WoWoViewPager
WoWoViewPager combines ViewPager and Animations to provide a simple way to create guide pages of the app. It supports some simple animations, namely:
- translation;
- scale;
- alpha;
- background color animations;
- gif-playing;
- SVG-drawing;
- path-drawing.
18. Lottie
Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as JSON with Bodymovin and renders them natively on mobile.
By its means, designers can create and ship beautiful animations without an engineer painstakingly recreating it by hand.
Lottie’s major advantage is the support of a great variety of After Effects features.
19. FerrisWheelView
FerrisWheelView is a library that allows implementing an animated Ferris Wheel.
To sum up
Depending on the situation, it is easier to create some animations with the help of the existing libraries, but whereas your idea has a lot of specific details, you will need a custom solution.
Those above will definitely favor the development process of your app, reducing financial and time inputs.
Nevertheless, you should always bear in mind that:
- animations should be functional, improving the user experience;
- only appropriate elements should be animated. Animating every detail makes no sense. Besides, implementing resource-intensive elements would decrease your app performance and affect interaction with the user;
- Render animations if you have such an opportunity, it will play into your hands as well.
Источник
Анимации в Android по полочкам (Часть 2. Комплексные анимации)
Приведённые в предыдущей части инструменты были относительно низкоуровневыми и в Android есть куда более простые способы добиться красивых анимаций не прибегая к прямому рисованию графики или изменению свойств объектов.
В этой части мы рассмотрим как можно минимумом усилий получить красивые анимации.
Часть 2. Комплексные анимации
1. Анимация изменений лэйаута (aka animateLayoutChanges)
Всё, что нам нужно сделать, чтобы добиться анимации как на гифке выше — это добавить флаг animateLayoutChanges в наш ViewGroup в xml. Теперь, когда мы удаляем или добавляем элемент в наш контейнер, либо изменяем его свойства, они автоматически будут анимированы.
Ладно, я немного слукавил когда говорил, что чтобы получить анимацию как на гифке выше, нужно всего лишь установить флаг. Добавление animateLayoutChanges на самом деле устанавливает LayoutTransition нашей ViewGroup. Но LayoutTransition по умолчанию анимирует только изменение видимости объектов в лэйауте. Поэтому если мы хотим изменять свойства объекта (например ширину и высоту) нужно включить эту опцию отдельно:
Теперь точно всё. Если захочется как-то кастомизировать это поведение, то у LayoutTransition есть метод setAnimator позволяющий задать свою собственную анимацию изменений. Ну самые хардкорные ребята всегда могут написать свой LayoutTransition .
• Применение:
Базовая анимация изменений объектов на сцене.
• Достоинства:
Минимальные трудозатраты
• Недостатки:
Слабая кастомизация
2. Transitions framework
Начиная с API 19 в Android появился новый фреймворк позволяющий создавать сложные анимации с участием большого количества элементов и минимумом кода.
Есть два основных варианта его использования:
1) Использование TransitionManager.beginDelayedTransition(ViewGroup)
Чтобы создать анимацию необходимо перед внесением изменений в наши View вызвать TransitionManager.beginDelayedTransition(ViewGroup) и передать в него ViewGroup, который мы хотим анимировать. Фрэймворк запомнит состояние View и запустит анимацию на следующем кадре.
2) Создание сцен
Создание анимации в этом случае сводится к созданию двух похожих xml, отвечающих за начальное и конечное состояние ваших анимаций. Соответственно, id объектов в xml должны совпадать, чтобы дать фреймворку возможность найти соответствие (На самом деле beginDelayedTransition тоже создаёт сцены, одну в момент вызова, а вторую на следующем кадре. После чего запускает анимацию между ними).
Кастомизация в Transitions framework достигается за счёт передачи объекта Transition вторым параметром. По умолчанию используется AutoTransition() , так что код ниже будет работать абсолютно так-же, как и код выше.
И если заглянуть внутрь AutoTransition можно заметить что анимации будут происходить в последовательно в следующем порядке:
— анимируются исчезающие объекты
— анимируются изменения размеров
— анимируются появляющиеся объекты
• Применение:
Анимация большого количества объектов
• Достоинства:
Минимальные трудозатраты
Доступная кастомизация
Источник