Reputation: 87
I am using the standard Android Canvas and a black color for the background. I would like it to randomly spawn white rectangles and move them vertically and horizontally.
I hope the question is clear and doable.
Upvotes: 0
Views: 554
Reputation: 10786
Sure, make a class containing information on a bunch of randomly spawned rectangles. When you randomly spawn a new one, which you'll want to do with a background thread. Invalidate that part of the view where the rectangle now exists.
Overload the onDraw(Canvas canvas) function for the view and have it, draw all the white rectangles every time it's called.
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);
}
}
Put somewhere in a view to override the onDraw(), remember to declare the paint for the rectanglePaint and make it white or whatnot. But that's the code. Save some background thread or something to do the randomly calling addRectangle();
Upvotes: 1
Reputation: 1029
Create white paint
Paint white=new Paint();
white.setColor(Color.WHITE);
Override onDraw(Canvas)
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
}
Upvotes: 0