Android 背景动画

这篇博客介绍了如何在Android中创建背景动画,使背景图片在屏幕上下左右循环移动。通过自定义View并使用线程和Handler更新图片坐标来实现这一效果。

        项目要实现背景动画,就是背景图片比屏幕大,然后通过动画实现背景图片的上下左右循环移动,用到很多方法,下面是我认为效果最好的一种:

代码:

        public class Draw extends View implements Runnable{


private Bitmap bmp;
private int left = 0;
private int top = 0;
private Handler handler;
private int dx = 1;
private int dy = 1;
public static boolean isRunning = true;
private boolean mark=true;

public Draw(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public Draw(Context context, AttributeSet attrs, int defStyle) {
         super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}

public Draw(Context context, AttributeSet attrs) {
super(context, attrs);
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.homeback);
handler = new Handler();
new Thread(this).start();
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawBitmap(bmp, left, top, null);
}

public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (left > (getWidth() - bmp.getWidth()+5) && mark) {
left = left - dx;
} else if (top > (getHeight() - bmp.getHeight()+5) && mark) {
top = top - dy;
if (top <= (getHeight() - bmp.getHeight()+5)){
mark = false;
}
} else if (left <= 0 && !mark) {
left = left + dx;
} else if (top <=0 && !mark) {
top = top + dy;
if (top >= 0)
mark = true;
}
handler.post(new Runnable() {

public void run() {
// TODO Auto-generated method stub
invalidate();
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}

}


注释:通过子线程实现图片坐标的变化

在xml将自定义的View写上就可以了:


<com.microimage.view.Draw 
     android:layout_width="wrap_content"
      android:layout_height="wrap_content"/> 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值