自定义控件 AnimationView 动画View

用四张图片 做动画,图片都放在res文件中了。

public class AnimationView extends View {
//声明属性
    Bitmap[] bitmap;
    int sleepTime = 1000;
    boolean isRunning = true;
    int currentImageIndex = 0;
    int viewWidth, viewHeight;
    Thread thread;

    //构造方法
    public AnimationView(Context context, AttributeSet attrs) {
        super(context, attrs);
        bitmap = new Bitmap[4];
        bitmap[0] = BitmapFactory.decodeResource(getResources(),
                R.drawable.logo1);
        bitmap[1] = BitmapFactory.decodeResource(getResources(),
                R.drawable.logo2);
        bitmap[2] = BitmapFactory.decodeResource(getResources(),
                R.drawable.logo3);
        bitmap[3] = BitmapFactory.decodeResource(getResources(),
                R.drawable.logo4);
        MyRunnable myRunnable = new MyRunnable();
        thread = new Thread(myRunnable);
        thread.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Bitmap drawImage = bitmap[currentImageIndex];
        int x = (viewWidth - drawImage.getWidth()) / 2;
        int y = (viewHeight - drawImage.getHeight()) / 2;
        Paint paint = new Paint();
        canvas.drawBitmap(drawImage, x, y, paint);
        Log.i("animationView", "onDraw x=" + x);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // TODO Auto-generated method stub
        super.onSizeChanged(w, h, oldw, oldh);
        viewHeight = h;
        viewWidth = w;
    }

    class MyRunnable implements Runnable {
        @Override
        public void run() {
            while (isRunning) {
                try {
                    currentImageIndex++;

                    if (currentImageIndex >= bitmap.length) {
                        currentImageIndex = 0;
                    }
                    // 工作线程中更新界面调postInvalidate();
                    // 主线程中更新界面调invalidate();
                    postInvalidate();
                    // invalidate();
                    Log.i("animationView", "currentImageIndex="
                            + currentImageIndex);
                    Thread.currentThread().sleep(sleepTime);
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }

        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值