我目前正在为android开发一个“混沌游戏”。对于那些不知道它是什么的人:你选择一些随机数,并且根据给定的规则,在画布上的某个地方画一个点;经过多次迭代,你得到一个形状,总是一样的。在这种情况下,它是一个蕨类植物。
这是我的代码:
MainActivity.java
public class MainActivity extends Activity {
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
setContentView(drawView);
}
}DrawView.java
public class DrawView extends View{
int viewWidth;
int viewHeight;
int iterations = 10000; // how many dots
int myColor;
Paint paint = new Paint();
Random rand = new Random();
public DrawView(Context context) {
super(context);
myColor = context.getResources().getColor(com.*****.******.*****.R.color.ferncolor); //Green
paint.setColor(myColor);
paint.setAntiAlias(true);
}
@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
super.onSizeChanged(xNew, yNew, xOld, yOld);
viewWidth = xNew;
viewHeight = yNew;
}
@Override
public void onDraw(Canvas canvas) {
Double x = rand.nextDouble();
Double y = rand.nextDouble();
Double random;
for(int i = 0; i < iterations; i++){
random = rand.nextDouble();
if(random < 0.01){
x = 0.0;
y *= 0.16;
}
else if(random < 0.86){
x = (0.85 * x) + (0.04 * y);
y = (-0.04 * x) + (0.85 * y) + 1.6;
}
else if(random < 0.93){
x = (0.2 * x) - (0.26 * y);
y = (0.23 * x) + (0.22 * y) + 1.6;
}
else{
x = (-0.15 * x) + (0.28 * y);
y = (0.26 * x) + (0.24 * y) + 0.44;
}
Double posx = viewWidth/2.0 + x*viewWidth/7.5;
Double posy = y*viewHeight/10.2;
canvas.drawCircle(posx.floatValue(), posy.floatValue(), (float) 0.5, paint); //drawing dot at (posx,posy), size 0.5, with custom paint
}
}
}我的问题是,你必须等待所有的观点被画出来,然后你才能看到视图。这往往会导致几秒钟尴尬的空白。我想要的是每次迭代(或者每次x次迭代,取决于我的迭代次数)之后的“刷新”。
我认为这可以通过线程实现,但我不知道如何实现。
有什么想法吗?
谢谢!
发布于 2013-12-15 16:43:16
可以通过调用视图的invalidate()方法强制视图重绘。因此,您可以尝试将其放在for循环的末尾。
更多信息,这里。
而且,如果你想画10000个点,你很可能只会在每500次迭代或其他什么的时候宣布无效.
https://stackoverflow.com/questions/20596911
复制相似问题