最近做了一个项目中,其中遇到这样的需求要求图片移动到手指触碰的地方。具体实现代码如下所示:
package com.example.plane;
import Android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity {
private int speed = 10;
private MyPlane plane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
plane = new MyPlane(this);
setContentView(plane);
// plane.setBackgroundResource(R.drawable.ic_launcher);
WindowManager manager = getWindowManager();
Display display = manager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
plane.currentX = metrics.widthPixels / 2;
plane.currentY = metrics.heightPixels / 2;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
plane.currentX=event.getX();
plane.currentY=event.getY();
plane.invalidate();
return super.onTouchEvent(event);
}
}
package com.example.plane;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class MyPlane extends View {
Bitmap plane;
public float currentX;
public float currentY;
public MyPlane(Context context) {
super(context);
plane = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher);
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint p = new Paint();
canvas.drawBitmap(plane, currentX, currentY, p);
}
}
以上所述是小编给大家介绍的Android中View跟随手指移动效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程网网站的支持!
您可能感兴趣的文章:Android自定义圆形View实现小球跟随手指移动效果Android实现拖动小球跟随手指移动效果Android自定义view圆并随手指移动Android实现View拖拽跟随手指移动效果Android自定义控件实现随手指移动的小球基于Android实现随手指移动的ImageViewAndroid自定义视图实现手指移动轨迹