欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中View跟随手指移动效果

程序员文章站 2024-02-21 10:37:01
最近做了一个项目中,其中遇到这样的需求要求图片移动到手指触碰的地方。具体实现代码如下所示: package com.example.plane; import...

最近做了一个项目中,其中遇到这样的需求要求图片移动到手指触碰的地方。具体实现代码如下所示:

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) {
/*float x = 0;
float y = 0;
switch (event.getaction()) {
case motionevent.action_down:
x = event.getx();
y = event.gety();
break;
case motionevent.action_move:
x = event.getx();
y = event.gety();
break;
case motionevent.action_up:
x = event.getx();
y = event.gety();
break;
}*/
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跟随手指移动效果,希望对大家有所帮助