繁体   English   中英

android如何用动画处理线程

[英]android how to handle thread with animation

如何throw any object(Stone) continuously throw any object(Stone) moving Horizontally object 我已经使用了一个可以连续使用翻译动画扔石头的线程,但内存使用非常多,我的设备在3-4分钟后变慢。如何解决dis问题?

我认为您最好实现自己的SurfaceView 在其中,您可以比使用视图动画更加费力地绘制动画对象(使用专用线程)。 (当然,您必须为此重写部分代码,但从长远来看,它可能是最好的)。
如果您觉得想要尝试SurfaceView ,我建议您查看android中的Lunar Lander示例。

例:

public class ThrowView extends SurfaceView implements SurfaceHolder.Callback, OnGestureListener{
    //The OnGestureListener can detect a fling motion.
    private class DrawingThread extends Thread{
        private final float timefactor = 0.0001f; //This is used to make the animation a bit slower. Play with this value if the animation seems too be to slow or too fast.
        private final float damp = 0.9; //This is used to slow down the object. If it stops too fast or slow, this is the value to change.
        private float stoneX = 0; //The x-coordinate of our stone object. Use this when drawing.
        private float stoneY = 0; //The y-coordinate of our stone object. Use this when drawing.
        @Override
        public void run(){
            while(running){
            Canvas c = null;
            try{
                c = surfaceHolder.lockCanvas(null);
                synchronized (surfaceHolder) { 
                    updatePhysics();
                    doDraw(c); //doDraw is not in this example, but it should essentially just draw our object at stoneX, stoneY.
                }
            }finally{
                if(c!=null) surfaceHolder.unlockCanvasAndPost(c); 
            }
            SystemClock.sleep(40);
        }
        private void updatePhysics(long time){
            //Calculate how much time has passed since last step:
            time1 = System.currentTimeMillis();
            dT = (time1 - time2)*timefactor;
            time2 = time1;

            //Move the stone in x depending on the time and velocity:
            stoneX += vX*dT;
            //Decrease the velocity:
            vX -= dT*damp:
        }
    }
    protected volatile float vX = 0; //This is the x-speed. To be able to throw in y too, just make another variable for that.
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        //This is our onFling, here we take the velocity of the users fling and set our variable to that.
        //Note that this value is based on pixels.
        vX = velocityX;
        return true;
    }
    @Override
    public boolean onDown(MotionEvent e) {
        //The onDown should return true so onFling can be activated:
        return true;
    }
}

该示例是根据Lunar Lander样本制作的,以便于使用。 这里省略了许多方法(这个例子不是必需的),但可以根据Lunar Lander实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM