Android animate character in SurfaceView - android

I want to animate a character (for eg run a dog) on screen. AnimationDrawable seemed a perfect fit for this, and AnimationDrawable requires an ImageView. How do I add and move around the ImageView in SurfaceView?
Thanks.

You don't need an ImageView.
If your animation is an XML Drawable, you can load it directly from the Resources into an AnimationDrawable variable:
Resources res = context.getResources();
AnimationDrawable animation = (AnimationDrawable)res.getDrawable(R.drawable.anim);
Then set it's bounds and draw on the canvas:
animation.setBounds(left, top, right, bottom);
animation.draw(canvas);
You also need to manually set the animation to run on it's next scheduled interval. This can be accomplished by creating a new Callback using animation.setCallback, then instantiating an android.os.Handler and using the handler.postAtTime method to add the next animation frame to the current Thread's message queue.
animation.setCallback(new Callback() {
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
return;
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
//Schedules a message to be posted to the thread that contains the animation
//at the next interval.
//Required for the animation to run.
Handler h = new Handler();
h.postAtTime(what, when);
}
#Override
public void invalidateDrawable(Drawable who) {
return;
}
});
animation.start();

With a SurfaceView it is your responsibility to draw everything within it. You do not need AnimationDrawable or any view to render your character on it. Take a look onto Lunar Lander example game from Google.

Related

How to change repeatedly the tint of an ImageView?

I'm working on a prototype of a Tap Game.
And I work on the animation when the player damages the monster.
The monster is only an ImageView, and I use this line to change the ImageView's tint to the color red (defined in the color.xml)
imageView.setColorFilter(this.getResources().getColor(R.color.damage));
My goal is to make the ImageView "blink" between the original ImageView and the ImageView with the red tint.
But I don't know how I can do this repeatedly.
Can you help me? (I hope I made myself clear - I'm French and my English is not very good)
The easiest:
public void blinkLimited(long started, long duration) {
if(duration > System.currentTimeInMillis() - started) return;
imageView.setColorFilter(this.getResources().getColor(R.color.damage));
imageView.postDelayed(new Runnable(){ public void run() {
imageView.setColorFilter(this.getResources().getColor(R.color.atention));
imageView.postDelayed(new Runnable(){ public void run() {
blinkLimited(started, duration);
}, 200);
}, 200);
}
Execute blinkLimited(System.currentTimeInMillis(), 2000) and you notice.

Animate change of view background not happening smoothly

I am trying to animate the back ground of my activity
What i have done is
ImageView image = (ImageView) findViewById(R.id.toggle_image);
final TransitionDrawable td = new TransitionDrawable( new Drawable[] {
getResources().getDrawable(R.drawable.welcomeimagetoggle1),
getResources().getDrawable(R.drawable.welcomeimagetoggle2)
});
image .setImageDrawable(td);
td.startTransition(3000);
td.reverseTransition(3000);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
td.startTransition(3000);
td.reverseTransition(3000);
handler.postDelayed(this, 3000);
}
}, 3000);
It's working properly but the problem is while the timer ends the change happening is to smooth , there is a sudden movement. How can i avoid that ?
I think you should use this library (DexMovingImageView) instead.
It offers some cool transitions (check their demo). In your case, use the DexCrossFadeImageView with multiple images.
Don't forget to make the window background of your activity transparent to avoid overdraw.
UPDATE : About the padding, check the scaletype. As for animation, here's KenBurnsView (ImageView animated by Ken Burns effect), Motion (ImageView with a parallax effect that reacts to the device's tilt) and finally LoyalNativeSlider (An image slider with many cool animations). Hope this helps!

Animate sprites using drawableAnmiation

I have a design question so I don't start off on the wrong way. I am planning to have a sprite where it animates moving and I want to move this sprite around (changing position once every second).
I noticed that some tutorial talk about having a game loop,, onDraw on Canvas, bitmap ..etc
However, I am thinking of using drawableAnimation where I specify the set of images to load in xml and call start on it. Then I can just draw at the position required every second ( no loop, it is more like listener that gets called every sec from different process).
Do you forsee an issue? Any problem with above method
Thank you
Drawable Animation requires a fixed frame animation. Think of it like a flip book. The drawable would have to be the entire size of your canvas and your sprite would have to be prerendered on top of some transparent background to achieve your affect. It also would require a large amount of texture memory depending on the size and number of frames.
The "game loop" as you stated is sort of what Android already provides in a way. Inside of the standard canvas setup you have your "main Thread". So with an entity like a Handler you could tick frames if you like.
i.e.
Handler handler;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
handler = new Handler();
handler.post(new Runnable() {
public void run() {
boolean isLastFrame = drawFrame();
if (!isLastFrame) {
handler.postDelayed(this, ONE_SECOND_MILLIS);
}
}
});
This is not the greatest really either.
You could also encapsulate your sprite inside a View or own custom Drawable and inside your onDraw() method, you would update your canvas.
public void onDraw(Canvas canvas) {
// clear canvas
mPaint.setColor(Color.WHITE);
canvas.drawPaint(mPaint);
// Draw current
mPaint.setColor(Color.BLACK);
canvas.drawRect(rect, mPaint);
}
public void moveSprite() {
rect.offset(3, 3);
invalidate();
}
You could also, if using a View, use an ObjectAnimator to translate the View from position (x1, y1) to (x2, y2).
public void moveTo() {
if (!moveNeeded) {
return;
}
View view = getMyView();
view.animate().x(1).y(1).setListener(new Animator.AnimatorListener() {
public void onAnimationCancel(Animator a) { }
public void onAnimationStart(Animator a) {
}
public void onAnimationEnd(Animator a) {
moveTo();
}
public void onAnimationRepeat(Animator a) {
}
});
}

invalidate() on custom View does not cause onDraw(Canvas c) to be called

For my activity i use 3 custom views stacked.
the lower one is a SurfaceView fullscreen, the middle one is derived from GridView and overrides onDraw to add custom graphic.
The top one is derived directly from View, sits in a corner of the screen and act as a knob to control the others two views (this is the problematic view).
to add a custom animation to this view, i used this pattern:
public class StubKnobView extends View{
private Drawable knob;
private Point knobPos;
private float rotation;
private boolean needsToMove;
public void moveKnob(){
/* ...various calculations... */
this.needsToMove=true;
invalidate(); //to notify the intention to start animation
}
private void updateAnimation(){
/* ........... */
this.needsToMove= !animationComplete;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
int saveCount=canvas.getSaveCount();
canvas.save();
canvas.rotate(this.rotation, this.knobPos.x, this.knobPos.y );
this.knob.draw(canvas);
canvas.restoreToCount(saveCount);
if(this.needsToMove){
updateAnimation();
}
}
}
ideally, if there is an animation pending, after each drawing cycle the view should auto invalidate.
right now this doesn't work, to force the animation i have to touch the screen to cause a onDraw cycle.
Using "show screen updates" of Dev tools I see that no screen invalidate/update cycle happen , apart when i click the screen.
specifying the dirty rect also ha no effect.
So, any idea where to look to know why this invalidate/draw cycle does not work the way is intended?
I encontered this situation, and also doubted that invalidate() doesn't make onDraw() called again.
After simplified the business codes, it's turn out that there is a dead loop - exactly too much iterations, which blocks the UI thread.
So, my advice is that make sure the UI thread going smoothly first.
Try something like this with a private class in your View. The idea is not to call invalidate() from within onDraw(). Instead, post it on the running queue. Instantiate the private class in your View constructor and then just call animateKnob.start() when you want the animation. The onDraw() can then just focus on drawing.
public void moveKnob(){
// update the state to draw... KnobPos, rotation
invalidate()
}
private class AnimateKnob{
public void start(){
// Do some calculations if necessary
// Start the animation
MyView.this.post( new Runnable() {
stepAnimation()
});
}
public void stepAnimation(){
// update the animation, maybe use an interpolator.
// Here you could also determine if the animation is complete or not
MyView.this.moveKnob();
if( !animationComplete ){
// Call it again
MyView.this.post( new Runnable() {
stepAnimation()
});
}
}
}

animation does not start in canvas on android

I'm working on a game that requires drawing to SurfaceView's
Canvas. I'm using SurfaceHolder to obtain Canvas to draw to, and
perform drawing in a separate thread. Everything I draw displays
correctly except for this one animation.
Here is the animation definition (it is in res/drawable/
my_animation.xml:
and here is how I draw it to the Canvas:
AnimationDrawable ad = (AnimationDrawable)getResources().getDrawable(R.drawable.my_animation);
ad.draw(canvas);
ad.start();
but only the first frame ever appears on the screen.
What am I missing?
Thank you
If I get the reference right, you have to assign your AnimationDrawable to an ImageView as the example from http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html demonstrates:
// Load the ImageView that will host the animation and
// set its background to our AnimationDrawable XML resource.
ImageView img = (ImageView)findViewById(R.id.spinning_wheel_image);
img.setBackgroundResource(R.drawable.spin_animation);
// Get the background, which has been compiled to an AnimationDrawable object.
AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
// Start the animation (looped playback by default).
frameAnimation.start()
In your case you did not assign your AnimationDrawable to any view so I suppose that's why it does not get updated. So you have to call AnimationDrawable.getFrame(int) manually.
If you are already using a separate thread why don't you involve also the code for your animation? This would render your code more consistent in my opinion.
Although this is an old question, i run into this problem too and figure out a walkaround, so i just post it here in case anyone searching about.
```java
final AnimationDrawable animationDrawable = ...;
final View v = new View(this) {
#Override
protected void onDraw(Canvas canvas) {
animDrawable.draw(canvas);
}
};
animationDrawable.setCallback(new Callback() {
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
v.removeCallbacks(what);
}
#Overridew
public void scheduleDrawable(Drawable who, Runnable what, long when) {
v.postDelayed(what, when - SystemClock.uptimeMillis());
}
#Override
public void invalidateDrawable(Drawable who) {
v.postInvalidate();
}
});
```
Animated drawables of all kinds (Transition, etc.) need a Callback to schedule redrawals. As zhang demonstrates, it is a simple interface for posting Runnables.
To support animated drawables in a custom view, you need two things:
pass your View to your animated Drawable's setCallback. Even base View implements Drawable.Callback, so there's no need to write your own wrapper.
override verifyDrawable to also return true for your animated Drawable.
As to why anyone would need that - I have just implemented animated drawable support in RecyclerView.ItemDecorations, how cool is that :-)
You are working with Canvas means, you are coding in low level. In low level u have to do everything. working with View (ImageView) means, it is high level.In ImageView already defined in low level on canvas how to deal with AnimationDrawable.
Lars Blumberg's answer is correct but the documentation is incorrect; you also need to take into account this: animation start issue

Categories

Resources