我一直关注YouTube上的一个视频,我可以通过按图像并四处移动来移动图像,但是起始位置在左上角,我尝试手动移动它,但仍然在同一位置我的活动中的代码。
任何帮助将不胜感激:)
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;
}
});
}
}
答案 0 :(得分:0)
这与算法有关,无论图像类型如何,我都在编写伪代码:
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
答案 1 :(得分:0)
只需转到xml文件并将布局重力设置为'center'