Android中View跟随手指移动效果
最近做了一个项目中,其中遇到这样的需求要求图片移动到手指触碰的地方。具体实现代码如下所示:
packagecom.example.plane; importAndroid.app.Activity; importandroid.os.Bundle; importandroid.util.DisplayMetrics; importandroid.view.Display; importandroid.view.KeyEvent; importandroid.view.Menu; importandroid.view.MenuItem; importandroid.view.MotionEvent; importandroid.view.View; importandroid.view.View.OnKeyListener; importandroid.view.View.OnTouchListener; importandroid.view.Window; importandroid.view.WindowManager; publicclassMainActivityextendsActivity{ privateintspeed=10; privateMyPlaneplane; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); plane=newMyPlane(this); setContentView(plane); //plane.setBackgroundResource(R.drawable.ic_launcher); WindowManagermanager=getWindowManager(); Displaydisplay=manager.getDefaultDisplay(); DisplayMetricsmetrics=newDisplayMetrics(); display.getMetrics(metrics); plane.currentX=metrics.widthPixels/2; plane.currentY=metrics.heightPixels/2; } @Override publicbooleanonTouchEvent(MotionEventevent){ /*floatx=0; floaty=0; switch(event.getAction()){ caseMotionEvent.ACTION_DOWN: x=event.getX(); y=event.getY(); break; caseMotionEvent.ACTION_MOVE: x=event.getX(); y=event.getY(); break; caseMotionEvent.ACTION_UP: x=event.getX(); y=event.getY(); break; }*/ plane.currentX=event.getX(); plane.currentY=event.getY(); plane.invalidate(); returnsuper.onTouchEvent(event); } } packagecom.example.plane; importandroid.content.Context; importandroid.graphics.Bitmap; importandroid.graphics.BitmapFactory; importandroid.graphics.Canvas; importandroid.graphics.Paint; importandroid.view.View; publicclassMyPlaneextendsView{ Bitmapplane; publicfloatcurrentX; publicfloatcurrentY; publicMyPlane(Contextcontext){ super(context); plane=BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher); setFocusable(true); } @Override protectedvoidonDraw(Canvascanvas){ super.onDraw(canvas); Paintp=newPaint(); canvas.drawBitmap(plane,currentX,currentY,p); } }
以上所述是小编给大家介绍的Android中View跟随手指移动效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!