项目要实现背景动画,就是背景图片比屏幕大,然后通过动画实现背景图片的上下左右循环移动,用到很多方法,下面是我认为效果最好的一种:
代码:
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"/>
这篇博客介绍了如何在Android中创建背景动画,使背景图片在屏幕上下左右循环移动。通过自定义View并使用线程和Handler更新图片坐标来实现这一效果。
611

被折叠的 条评论
为什么被折叠?



