通过触摸android旋转视图

时间:2018-09-25 14:51:58

标签: java android

通过旋转Android旋转视图触摸时旋转布局,但是当我按一号并用手指旋转时会发生奇怪的事情。它可以正常工作,但是当我按其他位置(如number2或number3或number4或任何其他圆圈number1圆圈)在我的手指下面时,为什么!

我想抓住任何圆圈并从中旋转形状 换一种方式,我想从触摸的地方旋转形状而不仅仅是形成

enter image description here

第一,我尝试了很多代码,却找不到解决方法

install Archive::Zip

XML代码:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.RotateAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.andreilisun.circular_layout.CircularLayout;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements OnTouchListener{
    private RelativeLayout wheel;
    private CircularLayout circle;
    TextView number1TextView,number2TextView;
    private double mCurrAngle = 0 ,mPrevAngle = 0;
    ArrayList<View>views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wheel = findViewById(R.id.rl_main_layout);
        circle = findViewById(R.id.cl_main_layout);
        number1TextView = findViewById(R.id.tv_main_number1);
        number2TextView = findViewById(R.id.tv_main_number2);
        views = new ArrayList<>();

        for(int i=0; i<circle.getChildCount(); i++){
            views.add(circle.getChildAt(i));
        }
        wheel.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(final View v, MotionEvent event) {
        final float xc = wheel.getWidth() / 2;
        final float yc = wheel.getHeight() / 2;

        final float x = event.getX();
        final float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE: {
                System.out.println("MOVe "+mCurrAngle);

                mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
                mPrevAngle = mCurrAngle;
                animate(mPrevAngle, mCurrAngle, 0);
                for(int i=0; i<views.size(); i++) {
                  //  if(views.get(i) instanceof TextView)
                    //animate2(-mCurrAngle, -mPrevAngle, 0, views.get(i));
                }
                break;
            }
        }
        return true;
    }

    private void animate(double fromDegrees, double toDegrees, long durationMillis ) {
        final RotateAnimation rotate = new RotateAnimation((float) fromDegrees, (float) toDegrees,
            RotateAnimation.RELATIVE_TO_PARENT, 0.5f,
            RotateAnimation.RELATIVE_TO_PARENT, 0.5f);
        rotate.setDuration(durationMillis);
        rotate.setFillEnabled(true);
        rotate.setFillAfter(true);
        wheel.startAnimation(rotate);
    }
}

1 个答案:

答案 0 :(得分:0)

您计算的旋转角度是相对于整个图像的角度。您需要保存与图像原始接触的角度,并相对于原始角度旋转它。

尽管实际上您执行此操作的整个方法都是错误的。您正在使用0毫秒动画?您应该只在视图上设置旋转矩阵。