ImageView 不在屏幕中央

ImageView is not at the center of the screen

我关注了 YouTube 上的一个视频,我可以通过按下图像并四处移动来移动图像,但起始位置在左上角,我尝试手动移动它但仍然在同一位置这是我 Activity 中的代码。

任何帮助将不胜感激:)

public class Game extends AppCompatActivity {

private ImageView Plane;
private ViewGroup RootLayout;
private int _xDelta;
private int _yDelta;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    RootLayout = (ViewGroup)findViewById(R.id.main3);
    Plane = (ImageView)RootLayout.findViewById(R.id.airplane);

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(280, 280);
    Plane.setLayoutParams(layoutParams);
    Plane.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) Plane.getLayoutParams();
                    _xDelta = X - lParams.leftMargin;
                    _yDelta = Y - lParams.topMargin;
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    break;
                case MotionEvent.ACTION_POINTER_UP:
                    break;
                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) Plane.getLayoutParams();
                    layoutParams.leftMargin = X - _xDelta;
                    layoutParams.topMargin = Y - _yDelta;
                    layoutParams.rightMargin = -250;
                    layoutParams.bottomMargin = -250;
                    Plane.setLayoutParams(layoutParams);
                    break;
            }

            RootLayout.invalidate();
            return true;
        }
    });

}

}

是关于算法的,我写的是伪代码,不管是什么类型的图片:

int nScreenWidth = FuncSW();
int nScreenHeight= FuncSH();

int nImageWidth  = FuncIW();
int nImageHeight = FuncIH();

SetImagePosition( nScreenWidth/2 - nImageWidth/2, nScreenHeight/2-nImageHeight/2 );
// SetImagePosition(xpos,ypos) where xpos is the image left pos, ypos is image the top pos

只需转到 xml 文件并将布局引力设置为 'center'