- AnimationDrawable ()
- Пример с анимацией
- Создание анимации в коде программы
- Изменяем прозрачность
- Анимация при загрузке приложения
- Копирование кадров и показ в обратном порядке
- Анимация градиентного фона
- Frame Animations in Android
- Frame Animations in Android
- Sequence of Images
- XML Drawables
- Animation-List
- Animated-Selector
- Set Up the ImageViews
- Starting the Animations
- Animation-List
- Animated-Selector
- Delightful Details
- Creating Frame by Frame Animations in Android
- 1. Identifying the Image Frames
- 2. Define Animation Sequence
- 3. Declare Activity Layout
- 4. Control the Animation Behaviour
AnimationDrawable ()
Кадровая (фреймовая) анимация — традиционная анимация при помощи быстрой смены последовательных изображений, как на киноплёнке. Данный вид анимации использует XML-файлы в каталоге res/anim/.
- графический ресурс для кадра
- продолжительность кадра
Данная анимация будет выполняться только для трёх кадров. При установке атрибута android:oneshot в true анимация повторится только один раз и после остановки будет содержать последний кадр. Если же атрибут установить в false, то анимация будет циклической. Данный XML-файл, сохраненный в каталоге res/anim проекта, можно добавить как фоновое изображение для компонента и затем запустить анимацию.
Пример с анимацией
Создадим новый проект и добавим на форму две кнопки для управления анимацией.
Для анимации подготовим заранее отобранные файлы, которые необходимо поместить в каталог res/drawable. Наша анимация будет состоять из восьми кадров. Время показа каждого кадра установим в 250 миллисекунд. Запишем наши настройки в XML-файл catanimation.xml в каталоге res/drawable.
Получить объект AnimationDrawable в коде программы можно так:
Управлять объектом AnimationDrawable можно через методы start() и stop().
Запустите приложение и посмотрите на анимацию. Надеюсь, вид кота, делающего упражнения, заставит вас с понедельника начать делать зарядку.
Создание анимации в коде программы
Также можно создавать анимацию в коде — достаточно загрузить последовательно ресурсы кадров и определить время показа для каждого кадра. В качестве примера создадим новый проект, взяв за основу предыдущее упражнение.
В основном классе определим два внутренних метода startFrameAnimation() и stopFrameAnimation(), которые будем вызывать при нажатии кнопок «Пуск» и «Стоп».
В методе startFrameAnimation() реализуем создание анимации. Надо получить кадры анимации в виде набора объектов Drawable, загрузив изображения из ресурсов. Для каждого кадра создается отдельный объект Drawable:
Созданные объекты BitmapDrawable необходимо добавить в объект AnimationDrawable методом addFrame(), который принимает два параметра: кадр анимации (объект Drawable) и продолжительность показа в миллисекундах.
Полный листинг будет следующим:
В методах я также использовал проверку на работающую анимацию (isRunning()), хотя и без этой проверки всё работало. Но мало ли что.
Результат будет тот же самый (теоретически). У меня в эмуляторе почему-то работали только первые три кадра. На форумах многие пишут, что у них выводится только первый кадр. Отсюда можно сделать вывод, что не нужно использовать программную анимацию, а использовать анимацию через XML. Статья писалась в 2012 году, возможно сейчас на эмуляторе таких проблем нет.
Изменяем прозрачность
Класс AnimationDrawable имеет метод setAlpha(), позволяющий изменять прозрачность кадров от 255 до 0. Модифицируем предыдущий пример. Добавим на форму метку и ползунок:
В коде программы добавим слушатель изменения ползунка в методе onCreate():
Анимация при загрузке приложения
В документации по кадровой анимации имеется предупреждение, что при запуске программы анимация не запустится, так как не все необходимые классы подгружаются в момент старта приложения. В нашем примере мы использовали нажатия кнопок для запуска и остановки анимации, поэтому нам удалось избежать этой проблемы. А что же делать, если нам необходимо запустить анимацию сразу?
В этом случае придётся усложнить код. Добавим новый класс:
А в основном классе из первого примера добавим строчку кода:
Теперь при запуске приложения анимация автоматически начнет проигрываться.
Также можно попробовать вызвать метод onWindowFocusChanged().
Ниже есть пример, где код вынесен в onResume().
Копирование кадров и показ в обратном порядке
Мы можем получить отдельные кадры анимации и выстроить новую цепочку. Добавим на экран второй компонент ImageView и запустим в нём анимацию в обратном порядке, скопировав все кадры из первой анимации.
На всякий случай предупрежу, что во всех примерах мы использовали фон: setBackgroundResource(), getBackground() и т.д. Если вы будете использовать атрибут android:src, то соответственно используйте getDrawable() и другие родственные методы.
У AnimationDrawable нет слушателей, позволяющих отслеживать конец анимации. Как вариант, рассчитайте самостоятельно количество кадров и их продолжительность и реализуйте свой способ.
Данный вид анимации подходит для небольших изображений с ограниченным количеством кадров. Если изображения будут большими и кадров слишком много, то наступит переполнение памяти. Помните об этом.
Анимация градиентного фона
Создадим ресурсы для цветов в colors.xml.
В папке drawable создайте три файла с именами gradient_1.xml, gradient_2.xml и т.д. Содержимое будет одинаковым, только меняйте имена ресурсов и углы: 0, 255, 45.
В той же папке drawable создайте ещё один файл gradient_animation_list.xml
Присвойте корневому контейнеру идентификатор и созданный ресурс, у меня корневым макетом был FrameLayout.
Источник
Frame Animations in Android
Frame Animations in Android
Animations add vivacity and personality to your apps. Let’s take a look at how to implement a subcategory of animations called “Frame Animations,” meaning that they’re drawn frame by frame.
In Google’s official Material Design spec, there’s an entire page dedicated to Delightful Details, which has wonderful examples of Frame Animations in action.
Nifty animations! Unfortunately, nothing on the page links to resources for actually creating those delightful details, so here I am to help! Specifically, we’re going to walk through making an empty heart animate into a filled-up heart, then vice versa. It’ll look something like this:
…beautiful, I know.
Sequence of Images
The idea behind a frame animation is simple: We’ll be cycling through a series of images very quickly, just like an old movie reel. The “frame” refers to a single image. Thus, the first step in creating a custom frame animation is to create a sequence of images.
We have two options here: we can use XML drawables (such as shape drawables) or actual image files. For the sake of simplicity, we’re going to use the following series of PNG images:
In a production application, we would also make sure to have images sized appropriately for different screen densities. For now, shove those images into the res/drawable-mdpi folder and call it a day. I would also recommend naming them in a self-descriptive way, such as ic_heart_0.png , ic_heart_1.png and so on. This way, we know the order of the images without having to view them.
I chose to name my heart images by their respective filled-up percentage, because I’m a nerd.
XML Drawables
Now that we have our images to cycle through, the next step is to define an XML Drawable for our animation. Once again, we are faced with two possibilities: the Animation-list and the Animated-selector.
Animation-List
Animation-list is the default Frame Animation of choice, as it was introduced in API 1. It works everywhere, and it’s simple. It just cycles through a sequence of provided images in a given order with given durations.
Here’s an example of an Animation-list for my heart filling up, placed in res/drawable/animation_list_filling.xml :
Each item in the list is just pointing to one of the images in our sequence from earlier. All we have to do is place them in the correct order and then add an appropriate duration in milliseconds.
And here’s an example of an Animation-list for my heart emptying, placed in res/drawable/animation_list_emptying.xml :
You might notice the android:oneshot=”true” in both of these code snippets, which is simply an attribute of the animation-list for playing the animation once and then stopping. If this is set to “false,” the animation will play on repeat.
In production, the 500ms duration is a long time, but I want to exaggerate the animations for demonstration purposes. Also note that five frames isn’t very many images for a smooth transition. The number of frames to use and how long to display them is a problem to solve on an individual-implementation basis. For a frame of reference, 15 frames at 15ms is very smooth.
Animated-Selector
Animated-selector is a bit more complex, as it’s state-based. Depending on the state of a View (such as selected or activated), the selector will animate to the correct state using provided Transitions. The Animated-selector is implemented only for Lollipop (and above), so we’re going to define our XML in the -v21 package.
Here is an example of the Animated-selector, placed in res/drawable-v21/selector.xml :
Take note of how it’s actually referencing our Animation-lists from earlier as Transitions.
This animated-selector works well, but we need to account for the non-Lollipop devices. We’re going to define a non-animated selector, placed in res/drawable/selector.xml :
Now our selector will work on any device. If tried on a pre-Lollipop device, the animated-selector will just just skip the Transitions and go directly to the end state, since we’re just using a normal selector. And of course, a Lollipop device will have our Transition that we defined in the animated-selector.
In the above snippet, the animated-selector cares about the android:state_activated attribute. Just like a normal selector, I have different items defined for the possible states. However, I also have transitions defined for how to animate between these different states. In this particular animation, I just pointed the transitions to the animation-list drawables that we defined earlier.
We now have four XML files: one for emptying the heart, one for filling the heart, and two selectors for transitioning between empty and full states.
Set Up the ImageViews
It’s time to set up some ImageViews for us to play with. Specifically, we’re going to have three ImageViews, one for each XML Drawable that we defined previously. Put the following code in a Layout of your choice and throw it in an Activity:
This is just a few ImageViews with unique ids and backgrounds pointing to our XML Drawables from earlier.
Starting the Animations
The behavior for starting the animations differs between the two implementations, so we’ll start with the animation-list.
Animation-List
In our Activity, we grab a reference to the ImageView and then start the animation, like so:
Here’s what that looks like :
Now for its partner code (identical except for the id):
And here’s what that part looks like:
Those code snippets can be put in onCreate (automatically begins when the Activity begins) or in an OnClickListener (waits for user interaction). The choice is yours!
Animated-Selector
When using the Animated-selector, the animation will trigger whenever the state-based condition is met for the selector. In our simple sample, we’re going to add a click listener to our ImageView in the onCreate method of our Activity:
When the user clicks on our heart, the heart will fill or empty, depending on the current state. Here’s a nice GIF of my heart looping back and forth forever (presumably with a user clicking at each full and empty state):
Be kind to our hearts, users!
Delightful Details
Frame Animations have the power to surprise and delight users, plus it’s fun to add little personal touches to an app. Go forth and animate!
Источник
Creating Frame by Frame Animations in Android
A frame animation created by moving an object little-by-little over several consecutive frames. In Android, we can create Frame Animation by swapping frames repeatedly, so that it appears continuous to the human eye and we feel that it is animated.
Frame is referred to an image. So to implement frame by frame animation in android, we needs to have set of images, which describes a motion. Now let’s move on and see how to implement frame by frame animation in Android
The following steps will guide you through step by step approach to create frame animation in Android.
1. Identifying the Image Frames
First step towards creating frame animation is to prepare a series of images with the individual frames of your animation. Add the images to your project’s drawable folder. In this example, I have used the following sequence of images.
2. Define Animation Sequence
Declare a XML file that defines the animation sequence that holds the list of drawables. Create a new file named frame_animation_list.xml and paste it to your project resource res/anim or res/drawable folder.
- Notice that in the above layout declaration, we are using AnimationDrawable class. This takes the list of Drawable resources and render them at specified intervals.
- Note that the AnimationDrawable class, loads all the images into memory before it starts animation.
- You must be careful about using this for images of larger size. Depending on the size of the images, you have to restrict the number of frames for making animation smoother.
3. Declare Activity Layout
Now declare an image view to your activity layout where the animation will be shown. In my example, I have declared an image view and two buttons Start and Stop to control the animation. Add the following snippet to your activity_main.xml file.
4. Control the Animation Behaviour
Now that we are ready with the animation sequence, we need to add this Drawable as a background resource for our ImageView. Use the following code snippet to set the AnimationDrawable as the background of the ImageView.
Once this is set, you can access this AnimationDrawable object by doing a get on the view object like this:
- Now we can control the behaviour of animation by using start() and stop() methods to start and stop the animation.
- You may use setOneShot() method runs the animation once and then stops.
- The addFrame(drawable, duration) method can be used to add a new frame by passing a Drawable object and sets its display duration.
Источник