欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android中View跟随手指移动效果

时间:2022-01-11 10:30:28|栏目:Android代码|点击:

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

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编程获取sdcard卡信息的方法

栏    目:Android代码

下一篇:android Textview文字监控(Textview使用方法)

本文标题:Android中View跟随手指移动效果

本文地址:http://www.codeinn.net/misctech/189833.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有