动画Android画布背景

时间:2015-01-19 22:04:53

标签: android animation canvas

我使用标准的Android Canvas和黑色作为背景。我希望随机产生白色矩形并垂直和水平移动它们 我希望这个问题清楚可行。

2 个答案:

答案 0 :(得分:1)

当然,创建一个包含一堆随机生成的矩形的信息的类。当你随机生成一个新的,你想要用后台线程。使矩形现在存在的视图部分无效。

重载视图的onDraw(Canvas画布)函数,并在每次调用时绘制所有白色矩形。

ArrayList<RectF> rectangles;
Paint rectanglePaint;

public void addRectangle(RectF addRectangle) {
    if (rectangles == null) rectangles = new ArrayList<>();
    rectangles.add(addRectangle);
    this.invalidate((int)addRectangle.left-1,(int)addRectangle.top-1, (int)addRectangle.right+1, (int)addRectangle.bottom+1);
}

public void translateRectangle(int index, float dx, float dy) {
    if (rectangles == null) return;
    RectF rect = rectangles.get(index);
    this.invalidate((int)rect.left-1,(int)rect.top-1, (int)rect.right+1, (int)rect.bottom+1);
    rect.set(rect.left+dx, rect.top +dy, rect.right+dx, rect.left+dy);
    this.invalidate((int)rect.left-1,(int)rect.top-1, (int)rect.right+1, (int)rect.bottom+1);
}

@Override
public void onDraw(Canvas canvas) {
    if (rectangles == null) return;
        for (RectF rect : rectangles) {
            canvas.drawRect(rect, rectanglePaint);
        }
}

将某个地方放在视图中以覆盖onDraw(),记得为rectanglePaint声明paint并将其设为白色或诸如此类。但这就是代码。保存一些后台线程或其他东西来随机调用addRectangle();

答案 1 :(得分:0)

创建白色油漆

Paint white=new Paint();
white.setColor(Color.WHITE);

覆盖onDraw(画布)

public void onDraw(Canvas c){
//if you want more, write a for loop here        c.drawRect(0,0,System.currentTimeMillis()%500,System.currentTimeMillis()%500,white);
// every time you invalidate this view, the rectangles will change their positions
}