首先需要找一张背景照片
具体原理就像这张图
Paste_Image.png
定义一个背景图片的类,包括了滚动的速度(speed),滚动的背景(bitmap),当前的高度(y);
包括几个方法:
beforeDraw:每次绘制前调用方法让它滚动一定距离(speed*density);
afterDraw:绘制后检查高度是否超出屏幕,如果超出,则让其置于顶部;
具体的代码如下
public class BgView {
private int y = 0;//背景当前的高度
private int speed = 2;//每一帧移动的速度
private Bitmap bitmap;//背景图片
public BgView(Bitmap bitmap) {
this.bitmap = bitmap;
}
public int getSpeed() {
return speed;
}
/**
* 绘制之前移动当前背景
*
* @param density
*/
public void beforeDraw(float density) {
y += (int)(speed * density);
}
/**
* 绘制完后检查是否超出屏幕,如果超出,则让它最下面在最顶上
*
* @param viewHeight 背景view的高度,
*/
public void afterDraw(int viewHeight) {
if (y >= viewHeight)
y = -1 * viewHeight;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public Bitmap getBitmap() {
return bitmap;
}
}
接下来是主的BgScrollView,用于绘制滚动的背景图
主要是onDraw方法,绘制完两个背景图后,通知下一次绘制
第一次绘制时,设置第一张图在最顶上,第二张图在屏幕上
具体代码如下
public class BgScrollView extends View {
private Paint paint;
private BgView firstBg;//第一个view
private BgView secondBg;//第二个view;
private boolean isFirst = true;
private float density = getResources().getDisplayMetrics().density;//获取密度
public BgScrollView(Context context) {
this(context, null);
}
public BgScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BgScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
paint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isFirst) {
Bitmap bg = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
bg = Bitmap.createScaledBitmap(bg, getWidth(), getHeight(), true);//将图片缩放为背景大小
firstBg = new BgView(bg);
firstBg.setY(0);//设置第一张图为0
secondBg = new BgView(bg);
secondBg.setY(getHeight() * -1);//设置第二张图在顶上
isFirst = false;
}
drawBack(canvas, firstBg);
drawBack(canvas, secondBg);
postInvalidate();
}
/**
* 绘制背景
*
* @param canvas
* @param bgView
*/
private void drawBack(Canvas canvas, BgView bgView) {
firstBg.beforeDraw(density);
canvas.drawBitmap(bgView.getBitmap(), 0, bgView.getY(), paint);
firstBg.afterDraw(getHeight());
}
}
网友评论