Moving an Image in circular motion based on touch events in android

杀马特。学长 韩版系。学妹 提交于 2019-11-27 17:03:28

问题


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:


  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))));


来源:https://stackoverflow.com/questions/20546897/moving-an-image-in-circular-motion-based-on-touch-events-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!