2017-08-26 48 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); 
}}