Moving an Image in circular motion based on touch

2019-01-23 21:53发布

I am trying to move an ImageView (not rotate). The movement is supposed to be on the edge of a circle. This circle is also an image view.

based on the onTouch, ACTION_MOVE event, I am trying to move it.

Noe the Dilema is that the use may not move the finger in a perfectly circular fashion but I would like to make sure that the image still moves around edge of this circle.

I am currently using the following inside ACTION_MOVE:

mCurrTempIndicator.setTranslationX(event.getX());
mCurrTempIndicator.setTranslationY(event.getY());

But this will not move in a perfect circle.

could someone please help.

UPDATE: code

@Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:


                        mInitialX = event.getX();
                        mInitialY = event.getY();

                    break;

                case MotionEvent.ACTION_MOVE:

                    mEndX = event.getX();
                    mEndY = event.getY();

                    float deltaX = mEndX - mInitialX;
                    float deltaY = mEndY - mInitialY;
                    double angleInDegrees = Math.atan(deltaY / deltaX) * 180 / Math.PI;

                    mInitialX = mEndX;
                    mInitialY = mEndY;

                    mCurrTempIndicator.setRotation((float)angleInDegrees);
                    mCurrTempIndicator.setTranslationX((float)(310*(Math.cos(angleInDegrees))));
                    mCurrTempIndicator.setTranslationY((float)(310*(Math.sin(angleInDegrees))));




                    break;

                case MotionEvent.ACTION_UP:
                    allowRotating = true;
                    break;
            }



            return true;
        }

1条回答
放荡不羁爱自由
2楼-- · 2019-01-23 22:47
  1. calculate the center Point of the Circle
  2. get the current touch point
  3. calculate the angle between center and new touch point
  4. Calculate the point on the circle using angle and radius of circle (x = r * cos(angle), y = r * sin(angle)).
  5. Reset the image position to the new point.

To get the angle use the below equation

deltaY = P2_y - P1_y
deltaX = P2_x - P1_x
angleInDegrees = arctan(deltaY / deltaX) * 180 / PI

//Code inside ACTION_MOVE case
mInitialX = event.getX();
mInitialY = event.getY();
float deltaX = circleCenter.x - mInitialX;
float deltaY = circleCenter.y - mInitialY;
double angleInRadian = Math.atan2(yDiff, xDiff);
PointF pointOnCircle = new PointF();
pointOnCircle.x = circleCenter.x + ((float)(circleRadius*(Math.cos(angleInRadian))));
pointOnCircle.y = circleCenter.y + ((float)(circleRadius*(Math.cos(angleInRadian))));
查看更多
登录 后发表回答