2017-08-26 24 views
2

我想每2秒产生一个圆圈,在这种情况下是5,但我无法得到它。应用程序不会每2秒创建一个圆圈,而是等待10秒钟,并将5个圆圈画在一起。我究竟做错了什么?谢谢。如何每2秒产生一个圆圈

public class Juego extends SurfaceView{ 

boolean isItOK = false; 

Paint paint; 
int CantidadDeEsferas = 5; 
int radio, alto, ancho; 

public Juego(Context context, @Nullable AttributeSet attrs) { 
    super(context, attrs); 

    paint = new Paint(); 
} 

public void onDraw(Canvas canvas){ 

    paint.setColor(Color.WHITE); 
    canvas.drawRect(0, 0, getWidth(), getHeight(), paint); 

    paint.setColor(Color.BLACK); 

    for (int i=0; i<CantidadDeEsferas; i++) { 

     Random r = new Random(); 
     alto = r.nextInt(canvas.getHeight()); 
     ancho = r.nextInt(canvas.getWidth()); 
     radio = r.nextInt(101 - 50) + 50; 
     canvas.drawCircle(ancho, alto, radio, paint); 
     run(); 
     isItOK = true; 
    } 
} 

public void run(){ 
    while (isItOK){ 
     try 
     { 
      Thread.sleep(2000); 
      isItOK = false; 
     } catch (InterruptedException e) { 

      e.printStackTrace(); 
     } 

    } 
} 

}

回答

0

通过调用onDraw有你暂停主线程运行。直到主线程返回到框架中的事件循环才显示绘图。你应该永远不要在主线程上调用睡眠或其他阻塞函数,因为(基本上,你的应用程序会出现冻结)。如果您想在2秒内完成某些操作,请创建一个Handler并使用postDelayed()向其发送消息。然后让消息的可运行增加视图设置为绘制的圆圈数量,然后使视图无效并在接下来的2秒内发布另一条消息。然后该视图应该在onDraw中绘制自己,检查该变量是否绘制了多少个圆。

0

什么有关

for (int i=0; i<CantidadDeEsferas; i++) { 

    Random r = new Random(); 
    alto = r.nextInt(canvas.getHeight()); 
    ancho = r.nextInt(canvas.getWidth()); 
    radio = r.nextInt(101 - 50) + 50; 
    canvas.drawCircle(ancho, alto, radio, paint); 
    run(); 
    while(isItOK); 
    isItOk = true; 
} 

的run()方法

public void run(){ 
    try 
    { 
     Thread.sleep(2000); 
     isItOK = false; 
    } catch (InterruptedException e) { 

     e.printStackTrace(); 
    } 
} 

,但我不喜欢你用

注意这样:这个类必须由另一个线程中运行(在背景)

0
public class MyView extends View { 

private Paint paint; 
private List<Point> points; 
private Handler handler; 
private Random random; 


public MyView(Context context) { 
    super(context); 
    init(); 
} 

public MyView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    init(); 
} 

public MyView(Context context, AttributeSet attrs, int defStyleAttr) { 
    super(context, attrs, defStyleAttr); 
    init(); 
} 

private void init() { 
    paint = new Paint(); 
    paint.setColor(Color.BLACK); 
    handler = new Handler(); 
    points = new ArrayList<>(); 
    random = new Random(); 
    drawCircles(); 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    for (Point point : points) { 
     canvas.drawCircle(point.x, point.y, 10, paint); 
    } 
} 

private void drawCircles() { 
    handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      for (int i = 0; i < 5; i++) { 
       Point point = new Point(); 
       point.set(random.nextInt(getHeight()), random.nextInt(getWidth())); 
       points.add(point); 
      } 
      invalidate(); 
      handler.postDelayed(this, 2000); 
     } 
    }, 2000); 
}}