6 - 3 - Graficos e Animação - Parte 3

Nos exemplos vista bolha que acabamos de ver, eu demonstrei um tipo simples de animação. Tomei um único ponto de vista, e eu mudei algumas de suas propriedades. Especificamente, a sua localização e orientação, e eu fiz isso durante um período de tempo.

In the bubble view examples that we just saw, I demonstrated a simple kind of animation. I took a single view, and I changed some of its properties. Specifically, its location, and orientation, and I did this over a period of time.

Animações como essa são bastante comuns. Os aplicativos geralmente animar alterações a coisa para as propriedades de uma vista como o seu tamanho, a sua posição, que é a transparência, é orientação, e muito mais.

Animations like this are fairly common. Applications often animate changes to thing to properties of a view like it's size, it's position, it's transparency, it's orientation, and more.

Para fazer a animação mais fácil Android fornece várias classes diferentes de apoio vista animação e três que vamos falar agora são a classe Transition Drawable para animar uma transição entre duas visões, a animação Drawable para a criação de animações quadro-a-quadro, ea classe de Animação para a criação de animações de interpolação, onde você especificar determinados quadros ou momentos de animação e Android interpola ou preenche os pontos entre os dois.

To make animation easier Android provides several different view animation support classes and three that we'll talk about now are the Transition Drawable class for animating a transition between two views, the Animation Drawable for creating frame-by-frame animations, and the Animation class for creating tween animations, where you specify certain frames or moments in the animation and Android interpolates or fills in the points in between.

Vejamos cada um deles. A primeira turma de animação que vamos discutir é a Drawable Transição. Essa classe especifica uma camada drawable dois, e quando ele é exibido, o usuário vê a primeira camada, em seguida, um pouco mais tarde, vê a segunda camada.

Let's look at each of these classes one at a time. The first animation class we'll discuss is the Transition Drawable. This class specifies a two layer drawable, and when it's displayed, the user sees the first layer, and then a bit later, sees the second layer.

Nossa aplicação de exemplo é chamado Gráficos Transição Drawable, e esta aplicação nos leva de volta aos gráficos Forma aplicações empate que vimos anteriormente. Mas desta vez, em vez de mostrar as duas formas ao mesmo tempo, esta aplicação apresenta pela primeira vez a forma colorida ciano mais à esquerda, que depois se desvanece em uma exibição da forma de cor magenta mais à direita. Vamos ver como isso funciona.

Our example application is called Graphics Transition Drawable, and this application takes us back to the Graphics Shape Draw applications that we saw earlier. But this time, instead displaying both shapes at the same time, this application first displays the leftmost cyan colored shape, which then fades into a display of the rightmost magenta colored shape. Let's see how that works.

Então aqui está o meu dispositivo, e quando eu iniciar a aplicação Gráficos Transição Drawable você verá a primeira forma sumindo na segunda. Então, vamos lá. Aqui está a primeira forma, e aqui está o segundo. Então, vamos dar uma olhada no código fonte. Então aqui está a aplicação Gráficos Transição Drawable, aberto no IDE.

So here's my device, and when I start up the Graphics Transition Drawable application you'll see the first shape fading into the second. So here we go. Here's the first shape, and here's the second. So let's take a look at the source code. So here's the Graphics Transition Drawable application, open in the IDE.

Agora vou abrir a atividade principal. Em OnCreate, este aplicativo carrega um drawable transição de um arquivo chamado shape_transition.xml. Vamos abrir esse arquivo. Este arquivo define um recurso de transição. Recursos desse tipo pode ter até duas marcas de item, e cada tag artigo descreve um drawable.

Now I'll open the main activity. In OnCreate, this application loads a transition drawable from a file called shape_transition.xml. Let's open that file. This file defines a transition resource. Resources of this type can have up to two item tags, and each item tag describes one drawable.

Neste caso, os drawables são as nossas formas de ciano e magenta familiares. Agora, de volta na atividade principal, o código chama conjunto crossfade habilitado com o parâmetro de verdade, e isso faz com que o primeiro drawable visualmente desaparecer no segundo drawable.

In this case, the drawables are our familiar cyan and magenta shapes. Now, back in the main activity, the code calls set crossfade enabled with the parameter true, and this causes the first drawable to visually fade into the second drawable.

Em seguida, o código define a transição, como o drawable para a vista da imagem, chamando imagem Jogo drawable, e, finalmente, ele chama início da transição, passando de um valor de 5000 para a duração da animação. O próximo tipo de animação que vamos falar é a Animação Drawable.

Next, the code sets the transition, as the drawable for the image view, by calling set image drawable, and then finally, it calls start on the transition, passing in a value of 5000 for the animation's duration. The next kind of animation that we'll talk about is the Animation Drawable.

Este desenhável anima uma série de outros drawables, mostrando cada uma, por algum período de tempo. Nosso próximo exemplo de aplicação é chamado Gráficos Animation Frame. Este aplicativo usa uma animação Drawable para exibir um tipo de tela de abertura, que se apresenta uma série de imagens em contagem regressiva para o início da aplicação principal.

This drawable animates a series of other drawables, showing each one for some period of time. Our next example application is called Graphics Frame Animation. This application uses an Animation Drawable to display a kind of splash screen, which itself presents a series of images counting down to the start of the main application.

Vamos ver o que isso faz. Então aqui está o meu dispositivo. Quando eu começar a gráficos quadro do aplicativo de animação, você verá uma série de imagens, contagem regressiva para a imagem final. Ok, vamos começar. Nove, oito, sete, seis, cinco, quatro, três, dois, um, e, finalmente, a imagem que todos nós temos estado à espera.

Let's see what this does. So here's my device. When I start up the graphics frame animation application, you'll see a series of images, counting down to a final image. Okay, let's get started. Nine, eight, seven, six, five, four, three, two, one, and finally, the image we've all been waiting for.

Então vamos ao código-fonte para esta aplicação. Então aqui está a aplicação de Animação Quadro de gráfico aberto no IDE. Agora vou abrir a atividade principal e no OnCreate este aplicativo carrega um Drawable Animação de um arquivo chamado view_animation.xml.

So let's go to the source code for this application. So here's the Graphics Frame Animation application open in the IDE. Now I'll open the main activity and in OnCreate this application loads an Animation Drawable from a file called view_animation.xml.

E, em seguida, ele define que drawable animação como plano de fundo em uma visão de imagem. Este código, em seguida, as lojas que Drawable em uma variável chamada Manim. E antes de ir para a frente, vamos dar uma olhada no arquivo view_animation.xml.

And then it sets that animation drawable as the background on an image view. This code then stores that drawable in a variable called mAnim. And before we go forward, let's take a look at the view_animation.xml file.

Então aqui está o arquivo view_animation.xml e este arquivo define um recurso lista animação. Este recurso contém uma lista de marcas de itens, onde cada marca representa um drawable, e neste caso, o primeiro drawable é apenas uma tela preta, e que exibe por um segundo, e isso é seguido por outros nove imagens, cada uma das quais é exibida também por um segundo.

So here's the view_animation.xml file and this file defines an animation list resource. This resource contains a list of item tags, where each tag represents a drawable, and in this case, the first drawable is just a black screen, and that displays for one second, and this is followed by nine other images, each of which is displayed also for one second.

Agora, de volta na atividade principal, o código de espera até que a janela em foco mudou método é chamado, e este método é chamado quando as aplicações ganhos janela ou perde o foco. Neste método, o código primeiro verifica se a janela está ganhando foco e se for isso, então começa a animação.

Now back in the main activity, the code waits until the on window focus changed method is called, and this method is called when the applications window gains or loses focus. In this method the code first checks whether the window is currently gaining focus and if it is it then starts the animation.

Próximo classe é a classe de animação, e esta classe é usada para criar animações em que as transformações são aplicadas para o conteúdo de um ponto de vista. Os aplicativos podem jogar com o timing dessas transformações a seqüência e combinar diferentes transformações para fazer animações mais complexas.

Next class is the animation class, and this class is used to create animations in which transformations are applied to the contents of a view. Applications can play with the timing of these transformations to sequence and combine different transformations to make more complex animations.

A aplicação gráfica Tween Animação demonstra a utilização da classe de animação. Quando esse aplicativo é executado, ele exibe uma visão bolha e então começa a animar uma série de mudanças para essa bolha. Vamos vê-lo em ação.

The graphics Tween Animation application demonstrates the use of the animation class. When this application runs, it displays a bubble view and then proceeds to animate a number of changes to that bubble. Let's see it in action.

Então aqui está o meu dispositivo. Quando iniciar a aplicação Gráficos Tween animação você verá a bolha, e então você verá uma série de transformações aplicadas a essa bolha. Você vai vê-lo desaparecer em, girar, mover, alterar seu tamanho, e, finalmente, desaparecer, e você também vai ver que o momento dessas transformações nem sempre é linear.

So here's my device. When I start up the Graphics Tween Animation application you'll see the bubble, and then you'll see a series of transformations applied to that bubble. You'll see it fade in, rotate, move, change its size, and finally, fade out, and you'll also see that the timing of these transformations is not always linear.

Ou seja, algumas transformações que acontecerá em um ritmo uniforme, alguns vão começar devagar e aumentar a velocidade, alguns vão começar rápido e, em seguida, reduzir a velocidade, alguns vão tanto acelerar e desacelerar em diferentes pontos na animação.

That is, some transformations will happen at a uniform pace, some will start slow and build up speed, some will start fast and then reduce their speed, some will both speed up and slow down at different points in the animation.

Agora, eu vou desacelerar o vídeo aqui um pouco, assim você pode ver esses efeitos de forma mais clara. Então, aqui vamos nós, primeiro a bolha desaparece dentro e próximo a bolha gira duas vezes, ficando mais rápido como ele vai. Agora, a bolha vai se mover, ultrapassar a sua posição final e em seguida, puxe um pouco para trás.

Now, I'll slow down the video here a little bit, so you can see these effects more clearly. So, here we go, first the bubble fades in and next the bubble rotates twice, getting faster as it goes. Now the bubble will move, overshoot its final position and then pull back a bit.

Depois disso, a bolha vai encolher um pouco antes de rapidamente dobrar de tamanho e, finalmente, a bolha desaparece de vista, de forma rápida no início, e depois mais lentamente perto do fim. Vamos dar uma olhada no código fonte para esta aplicação.

After that, the bubble will shrink a bit before quickly doubling its size, and finally the bubble fades out of view, quickly at first, and then more slowly near the end. Let's take a look at the source code for this application.

Então aqui está a aplicação Gráficos Tween Animação aberto no IDE. Agora, eu vou abrir a atividade principal. E este aplicativo define o, chama setContentView, passando o arquivo main.xml.

So here's the Graphics Tween Animation application open in the IDE. Now, I'll open the main activity. And this application sets the, calls setContentView, passing in the main.xml file.

E, em seguida, ele encontra uma visão imagem nesse layout. E depois que ele lê uma animação a partir do arquivo view_animation.xml que é armazenado no diretório res / Anim. Aqui está o recurso e aninhada dentro da tag conjunto existem várias outras marcas, cada uma das quais indica uma transformação específica para ser aplicada à vista.

And then it finds an image view in that layout. And after that it reads an animation from the view_animation.xml file which is stored in the res/Anim directory. Here's the resource and nested within the set tag there are several other tags, each of which indicates a specific transformation to be applied to the view.

A primeira é uma transformação alfa, a duração da animação é de três segundos. Vai desde um alfa igual a zero, ou completamente transparente, de um alfa de um, completamente opaca. A transformação também usa o interpolador linear, de modo que o efeito é aplicado uniformemente em toda a animação.

The first is an alpha transformation, the duration of the animation is three seconds. It goes from an alpha of zero, or completely transparent, to an alpha of one, completely opaque. The transformation also uses the linear interpolator, so the effect is applied uniformly throughout the animation.

A etiqueta a seguir é uma transformação de rotação. A duração está definida a quatro segundos, mas ele também está definido para iniciar somente após três segundos se passaram. Assim, a primeira transformação ocorrerá e acabamento, e então este será iniciado.

The next tag is a rotate transformation. The duration is set to four seconds, but it's also set to start only after three seconds have passed. So, the first transformation will occur and finish, and then this one will start up.

Esta animação vai de 0 a 720 graus, ou duas voltas completas, e seu interpolador acelera, ou velocidades, como a animação prossegue e você pode olhar para todas as outras tags em seu próprio país quando nós fazer uma pausa.

This animation goes from 0 to 720 degrees, or two full turns, and its interpolator accelerates, or speeds, up as the animation proceeds and you can look at all the other tags on your own when we take a break.

Voltando agora para a atividade principal, vamos para o foco na janela método alterado. Mais uma vez, este código verifica para ver se a janela está ganhando foco, e se assim for, ele começa a animação. O último conceito que eu vou falar é sobre animação propriedade.

Going back now to the main activity, let's go to the on window focus changed method. Again, this code checks to see if the window is currently gaining focus, and if so, it starts the animation. The last concept I'll talk about is property animation.

Os exemplos anteriores mostraram classes que são projetados para animar um conjunto de alterações de propriedade simples de pontos de vista. Mas às vezes, você deseja animar mais do que apenas aquelas coisas e apoiar que, Android desenvolveu um sistema para a mudança geral, propriedades de objetos genéricos durante um determinado período de tempo, e este sistema de animação de propriedades tem vários componentes.

The previous examples showed classes that are designed to animate a set of simple property changes on views. But sometimes, you want to animate more than just those things and to support that, Android has developed a system for changing general ,properties of generic objects over a given period of time, and this system of Property Animation has several components.

Em primeiro lugar, existe um valor de desenhos animados, e esta é a principal classe que controla a animação. O Valor de desenhos animados contém um interpolador de tempo que determina como os valores variam como uma função do tempo.

First, there is a Value Animator, and this is the main class that controls the animation. The Value Animator contains a time interpolator which determines how values change as a function of time.

Por exemplo, ao longo do tempo é que as mudanças acontecem de maneira uniforme, eles acelerar, desacelerar, ou usar uma combinação dos dois? Valor Animator também define uma interface ouvinte chamado Animator Atualização Listener, e esta interface define o método de atualização de animação em que é chamado sempre que um novo quadro de animação é criado.

For instance, over time do the changes happen uniformly, do they speed up, slow down, or use some combination of the two? Value Animator also defines a listener interface called Animator Update Listener, and this interface defines the on animation update method which gets called each time a new animation frame is created.

E, finalmente, enquanto o Android sabe como animar os valores de tipos comuns, como geradores de imagens ou carros alegóricos, que não sabe como animar tipos personalizados que você criar. Então, se você precisa para animar seus próprios tipos, ou animar os tipos existentes de novas maneiras que você pode implementar o tipo de avaliador de Interface.

And lastly, while Android knows how to animate the values of common types, like imagers or floats, it doesn't know how to animate custom types that you create. So if you need to animate your own types, or animate existing types in new ways you can implement the Type Evaluator Interface.

Esta interface define um método de avaliar que é chamada para definir os valores de animação em um determinado ponto na animação. A última peça de animação propriedade é o Animator Set Classe.

This interface defines an Evaluate method that gets called to set the animation values at a particular point in the animation. The last piece of property animation is the Animator Set Class.

Esta classe permite que você combine objetos animação, como o valor animador que acabamos de discutir, em animações mais complexas. Então, vamos olhar para alguns exemplos de aplicações que fazem uso de animação propriedade.

This class allows you to combine animator objects, like the value animator we just discussed, into more complex animations. So let's look at some example applications that make use of property animation.

A primeira dessas aplicações é chamada Graphics Value Animator, e este aplicativo usa um valor animador para animar uma mudança na cor de uma visão imagem de fundo. Vamos assistir a esta aplicação.

The first of these applications is called Graphics Value Animator, and this application uses a value animator to animate a change in the background color of an image view. Let's watch this application.

Então aqui está o meu dispositivo. Vou agora iniciar a aplicação animador valor gráficos. E como você pode ver, apresenta um único botão rotulado Animar. Ao pressionar esse botão, um retângulo vermelho irá aparecer no meio da tela, e durante um período de cerca de dez segundos, esse retângulo muda de cor até que seja finalmente azul. Vou pressionar o botão agora.

So here's my device. I'll now start up the graphics value animator application. And as you can see it presents a single button labeled Animate. When I press that button, a red rectangle will appear in the middle of the display, and over a period of about ten seconds, that rectangle will change color until it's finally blue. I'll press the button now.

Há o retângulo vermelho. E agora vamos ver como ele lentamente se torna azul. Vamos abrir o código-fonte e ver como nós fizemos isso. Então aqui está a aplicação animador valor gráficos aberto no IDE. Agora vou abrir a atividade principal.

There's the red rectangle. And now let's watch as it slowly turns blue. Let's open the source code and see how we did that. So here's the graphics value animator application open in the IDE. Now I'll open the main activity.

Este aplicativo é iniciado, definindo dois valores inteiros, que representam os pontos inicial e final para a animação. O primeiro valor é a representação inteira de cor vermelha. O segundo valor é a representação inteiro da cor azul.

This application starts by setting two integer values, which represent the starting and ending points for the animation. The first value is the integer representation of the color red. The second value is the integer representation of the color blue.

Em OnCreate, o código cria um botão que vai iniciar a animação, e como você pode ver aqui, quando o botão é clicado, o método de animação de início é executado. Vamos olhar para esse método. Aqui, o método de animação início cria um valor animado objeto chamado anim, e ele criou esse objeto chamando os animadores valor do método do objeto.

In OnCreate, the code creates a button that will start the animation, and as you see here, when the button is clicked, the start animation method is run. Let's look at that method. Here, the start animation method creates a value animated object called anim, and it created that object by calling the value animators of object method.

O primeiro parâmetro para este método é um avaliador tipo, neste caso, o tipo de avaliador é, na verdade, um, um avaliador ARGB objecto, e esta classe sabe como interpolar as representações inteiros de cores. O segundo eo terceiro parâmetros para o método de objeto são os pontos inicial e final para a animação, as cores vermelho e azul.

The first parameter for this method is a type evaluator, in this case the type evaluator is actually a, an ARGB evaluator object, and this class knows how to interpolate the integer representations of colors. The second and third parameters for the of object method are the starting and ending points for the animation, the colors red and blue.

Em seguida, o código adiciona um animador Atualização Listener e que vai ser chamado de volta cada vez que novos quadros de animação são criados e que o código chama o método Get animado valor para recuperar o valor da cor atual, e então ele faz com que a cor a cor do fundo visualização da imagem, o que é mostrado no layout.

Next the code adds an Animator Update Listener and that is going to be called back each time new animation frames are created and that code calls the Get Animated Value method to retrieve the current color value, and then it makes that color the background color of the image view, which is shown in the layout.

E, por último este código define a duração de dez segundos para a animação, e depois começa a animação em execução. Vamos também olhar para uma segunda aplicação animação propriedade, chamada Gráficos Propriedade Vista Animator.

And lastly this code sets the duration of ten seconds for the animation, and then starts the animation running. Let's also look at a second property animation application, called Graphics View Property Animator.

Esta aplicação irá implementar o mesmo aplicativo que criamos para a aplicação Gráficos Tween animação. Você vai ver uma bolha que se desvanece em, gira, move-se, redimensiona, e depois desaparece. E esta versão do aplicativo, no entanto, vai usar a exibição de propriedade animador classe, que é uma espécie de animador simplificada para apenas exibir as propriedades. Vamos ver o que a aplicação em ação.

This application will implement the same application we created for the Graphics Tween Animation application. You'll see a bubble that fades in, rotates, moves, resizes, and then fades out. And this version of the application, however, will use the view property animator class, which is a simplified kind of animator for just view properties. Let's see that application in action.

Então aqui está o meu dispositivo. E eu vou iniciar a aplicação Gráficos Propriedade Vista Animator. E vamos ver como a bolha passa por uma série de transformações. Aqui vamos nós Vamos abrir o código-fonte para esta aplicação.

So here's my device. And I'll start up the Graphics View Property Animator application. And we'll watch as the bubble goes through a series of transformations. Here we go. Let's open up the source code for this application.

Então aqui está a vista de gráficos aplicação Propriedade Animator aberto no IDE. Agora vou abrir a atividade principal. E vamos rolar até a janela em foco método alterado. Quando este método é chamado, o aplicativo garante que a janela de atividade está ganhando foco e se assim for, ele chama o método run do fade in objeto, e que fade in objeto é um executável.

So here's the Graphics View Property Animator application open in the IDE. Now I'll open the main activity. And let's scroll over to the on window focus changed method. When this method is called, the application insures that the activity window is gaining focus and if so, it calls the run method of the fade in object, and that fade in object is a runnable.

Agora dentro de seu método de execução, as suas ligações com código animar a visualização da imagem, que retorna um objeto de exibição de propriedade de animação. Este objeto, ou esta classe, usa uma interface fluente, como o que vimos com as notificações da área de notificação. E assim você pode construir uma animação por aderência em vários chamadas de método.

Now inside its run method, its code calls animate on the image view, which returns a view property animator object. This object, or this class, uses a fluent interface, like what we saw with the notification area notifications. And so you can build an animation by tacking on various method calls.

Neste caso, a próxima chamada está definido para duração de três segundos, em seguida, definir interpolador ao interpolater linear, em seguida, uma chamada para o método alfa para alterar a transparência para totalmente opaco e, em seguida, uma chamada final que conta a Propriedade Vista Animator que quando esta animação termina ele deve invocar o método de execução de outro chamado rotação executável.

In this case, the next call is set duration to three seconds, then set interpolator to the linear interpolater, then a call to the alpha method to change the transparency to fully opaque and then a final call which tells the View Property Animator that when this animation ends it should invoke the run method of another runnable called rotate.

E, como você provavelmente pode adivinhar, esta rotação executável cria o passo de rotação da animação, e então ele acaba chamando a etapa de movimento da animação, e isso continua até que todas as etapas foram concluídas. Então, isso é tudo por nossa lição em gráficos e animação. Vejo você na próxima vez para uma lição sobre multi-toque e gestos. Vejo você, então.

And, as you can probably guess, this rotate runnable creates the rotation step of the animation, and then it ends by calling the movement step of the animation, and this continues until all of the steps have been completed. So that's all for our lesson on graphics and animation. See you next time for a lesson on multi-touch and gestures. See you then.

Comentários

Postagens mais visitadas deste blog

Rails CanCan

Meus insights mais valiosos sobre criptomoedas para 2018 e além

Como pegar a senha do Whatsapp de um Android ou Iphone