我想在android中在1秒内显示60种不同的颜色。我怎么能这样做,所有颜色的显示持续时间(16ms)在1秒内是相同的?
答案 0 :(得分:1)
您可以在自定义View
中实现所需,您可以在invalidate()
次调用中调用onDraw()
:
int framesToRedraw = 0;
public void startAnimation(int frames){
framesToRedraw = frames;
this.invalidate();
}
/**
* onDraw override.
* If animation is "on", view is invalidated after each redraw
* to make android redraw it on the next frame
*/
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (framesToRedraw > 0) {
// generate new color randomly
float[] hsvColor = {0, 1, 1};
hsvColor[0] = random.nextFloat() * 360f;
this.setBackgroundColor(Color.HSVToColor(hsvColor));
framesToRedraw--;
this.invalidate(); // force the view to be redrawn on each frame
}
}
答案 1 :(得分:0)
您可以使用Handler
类来管理延迟执行。 Here你有一个例子,说明如何使用它来每n毫秒生成一个计时器。
final Handler handler = new Handler();
handler.postDelayed(new Runnable(){
private static final long INTERVAL = 16L;
private long time = 0;
@Override
public void run(){
time += INTERVAL;
if(time <= 1000){
handler.postDelayed(this, INTERVAL); //Make sure you are calling it after 16 millis
}
// Change your color here
changeColor();
}
}, INTERVAL);
答案 2 :(得分:0)
你已经有了数学,所以试试简单的风格
//assume im in a different Thread
for(int i=0; i < 17; i++){
Thread.sleep(16); // add try catch
Color c = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); }
非常简单