Apply an Animation on a Drawable in Android
I am adding a glow animation effect to a logo. So far, I have managed to get the glow image behind the logo, using a LayeredDrawable, but I can't figure out how to animate it. I have found that AlphaAnimation would achieve the desired effect, but unfortunately I can only ap开发者_StackOverflow中文版ply it on Views, not Drawables. How can I achieve this effect?
Simple example
final ImageView imageView = (ImageView) findViewById(R.id.animatedImage);
final Button animated = (Button) findViewById(R.id.animated);
animated.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Drawable drawable = imageView.getDrawable();
if (drawable.getAlpha() == 0) {
ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(drawable, PropertyValuesHolder.ofInt("alpha", 255));
animator.setTarget(drawable);
animator.setDuration(2000);
animator.start();
} else {
ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(drawable, PropertyValuesHolder.ofInt("alpha", 0));
animator.setTarget(drawable);
animator.setDuration(2000);
animator.start();
}
}
});
Method getAlpha()
add in api 19. But it's not a big restriction, you can save the status in a local variable. ObjectAnimator
add in Android 3.0 (api 11),maybe old version Android you can use nineoldandroids. I didn't test with nineoldandroids.
Android 3.0 introduced Property Animations.
Unfortunately, this is limited to Android 3.0 and up which won't get on phones any time soon.
Thank you @AndreyNick, it works like a charm! I've used it also for a LayerDrawable for animating just one Drawable (a layer) into it. This is the code, maybe could be useful for someone:
Drawable[] layers = new Drawable[2];
layers[0] = new ColorDrawable(Color.RED);
BitmapDrawable bd = new BitmapDrawable(activity.getResources(), bitmap);
bd.setGravity(Gravity.CENTER);
Drawable drawLogo = bd;
layers[1] = drawLogo;
LayerDrawable layerDrawable = new LayerDrawable(layers);
layers[1].setAlpha(0);
((AppCompatActivity) activity).getSupportActionBar().setBackgroundDrawable(layerDrawable);
ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(layers[1], PropertyValuesHolder.ofInt("alpha", 255));
animator.setTarget(layers[1]);
animator.setDuration(2000);
animator.start();
I needed to create a drawable for the Action Bar with:
- a layer (0) which is a background color and
- a layer (1) with the logo in the middle of it (with fade animation)
I load the logo with Picasso and I like to animate it when has been loaded (bitmap onBitmapLoaded callback).
I hope this could help!
I'm using an Animation on the ImageView displaying the drawable. I think this should be possible in your case too.
精彩评论