在android中移动圈子

时间:2012-11-13 11:32:54

标签: java android

我有一项任务。这是绘制一些(多个)圆圈在屏幕上移动。他们必须在点击它们后开始移动。我的代码只有一个圆圈。告诉我如何执行此任务的方式,例如,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);  
        }
    }
}

2 个答案:

答案 0 :(得分: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;

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

}

答案 1 :(得分:0)

您需要使用不同的centerx,centerY,Radius和p

调用绘制圆圈5次
相关问题