其他分享
首页 > 其他分享> > Android 学习动画 — SurfaceView动画【II】

Android 学习动画 — SurfaceView动画【II】

作者:互联网

效果图:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

慢慢的绘制出来,从左往右一帧一帧的绘制而成

新建一个 class,SurfaceViewAnim.java:

public class SurfaceViewAnim extends SurfaceView implements SurfaceHolder.Callback,Runnable {
    private SurfaceHolder mHolder;  //  声明SurfaceHolder
    private Canvas mCanvas;
    private boolean isDrawing;  //控制绘图线程
    private Paint paint;        //  画笔对象
    private Bitmap snail;   //  实现动画的图片对象
    private int snail_X;        //  动画元素的起始X坐标

    public SurfaceViewAnim(Context context) {
        super(context);
        snail = BitmapFactory.decodeResource(getResources(),R.drawable.ic_one);

        //  为了得到屏幕的宽度
        DisplayMetrics dm2 = getResources().getDisplayMetrics();
        int width = dm2.widthPixels;

        snail_X = width;    //  起始 X 坐标赋值为当前屏幕宽度值,即屏幕最右边
        paint = new Paint();
        mHolder = this.getHolder(); //  获取SurfaceHolder 对象
        mHolder.addCallback(this);  //  添加 Callback 接口
        
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isDrawing = true;
        new Thread(this).start();   //  启动绘图的线程
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isDrawing = false;  //  终止绘图线程
    }

    public void run(){
        while (isDrawing){
            snail_X--;      //  绘图元素属性修改,此处为修改其 X 坐标
            if (snail_X <= 0){  //  到达最左边后,不再移动
                snail_X = 0;
            }
            mydraw();       //  绘图
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void mydraw() {
        try {
            mCanvas = mHolder.lockCanvas();     // 锁定面板,开始绘图
            paint.setColor(Color.WHITE);
            mCanvas.drawRect(0,0,getWidth(),getHeight(),paint); //  绘制背景
            mCanvas.drawBitmap(snail,snail_X,100,paint);    //  绘图
        }catch (Exception e){

        }
        finally {
           if ( mCanvas != null){
               mHolder.unlockCanvasAndPost(mCanvas);    //  解锁花瓣,推送到界面
           }
        }
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    SurfaceViewAnim anim;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        anim = new SurfaceViewAnim(this);
        setContentView(anim);   //  设置 anim 为显示视图
    }
}

activity_main.xml,不变

点击运行即可

标签:动画,snail,int,void,private,II,SurfaceHolder,Android,public
来源: https://blog.csdn.net/qq_27494201/article/details/96618579