1

我有一个任务。它是在屏幕上绘制一些(多个)圆圈。单击它们后,它们必须开始移动。我只有一个圆圈的代码。给我怎么做这个任务的方法,比如5圈。提前致谢!

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }

    class MyView extends View {
        //public    Paint c;
        public  Paint p;

        private static final int RADIUS = 46;

        private int centerX;
        private int centerY;
        private int speedX = 50;
        private int speedY = 40;
        //private Paint paint; // Создай его где-нибудь там в конструкторе


        public MyView(Context context) {
            super(context);
            p = new Paint();
            p.setColor(Color.GREEN);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldW, int oldH) {
            centerX = w / 2;
            centerY = h / 2;
        }

        protected void onDraw(Canvas c) {
            int w = getWidth();
            int h = getHeight();
            centerX += speedX;
            centerY += speedY;
            int rightLimit = w - RADIUS;
            int bottomLimit = h - RADIUS;

            if (centerX >= rightLimit) {
                centerX = rightLimit;
                speedX *= -1;
            }
            if (centerX <= RADIUS) {
                centerX = RADIUS;
                speedX *= -1;
            }
            if (centerY >= bottomLimit) {
                centerY = bottomLimit;
                speedY *= -1;
            }
            if (centerY <= RADIUS) {
                centerY = RADIUS;
                speedY *= -1;
            }

            c.drawCircle(centerX, centerY, RADIUS, p);
            postInvalidateDelayed(200);  
        }
    }
}
4

2 回答 2

1

你必须改变这部分:

  private int centerX;
  private int centerY;
  private int speedX = 50;
  private int speedY = 40;

并将其转换为

class Circle {
  private int centerX;
  private int centerY;
  private int speedX = 50;
  private int speedY = 40;
  // add constructor here and other things
};

然后收集你的圈子:ArrayList<Circle> circles,然后代替

centerX += speedX;
centerY += speedY;
int rightLimit = w - RADIUS;
int bottomLimit = h - RADIUS;

if (centerX >= rightLimit) {
  centerX = rightLimit;
  speedX *= -1;
}
if (centerX <= RADIUS) {
  centerX = RADIUS;
  speedX *= -1;
}
if (centerY >= bottomLimit) {
  centerY = bottomLimit;
  speedY *= -1;
}
if (centerY <= RADIUS) {
  centerY = RADIUS;
  speedY *= -1;
}

你必须为每个圈子都这样做,比如

for( i=0; i<circles.size(); i++) {
    circles[i].centerX += circles[i].speedX;
    circles[i].centerY += circles[i].speedY;

    // и так далее...

}

于 2012-11-13T11:39:13.730 回答
0

您需要使用不同的 centerx、centerY、Radius 和 p 调用 draw circle 5 次

于 2012-11-13T11:40:08.187 回答