public class dragsurfaceview extends surfaceview implements surfaceholder.callback,runnable{ private int screenw; //屏幕宽度 private int screenh; //屏幕高度 private float cx = 100; //默认x坐标 private float cy = 100; //默认y坐标 private bitmap mbitmap; private surfaceholder msurfaceholder = null; private thread thread = null; public dragsurfaceview(context context,@nullable attributeset attrs) { super(context,attrs); msurfaceholder = getholder(); msurfaceholder.addcallback(this); mbitmap=getbitmapresources(context,r.drawable.x1); thread=new thread(this); } public static bitmap getbitmapresources(context context,int resid){ return bitmapfactory.decoderesource(context.getresources(),resid); } protected void mydraw() { //获取canvas实例 canvas canvas = msurfaceholder.lockcanvas(); //将屏幕设置为白色 canvas.drawcolor(color.white); //绘制图片和位置 canvas.drawbitmap(mbitmap,cx,cy,null); //将画好的画布提交 msurfaceholder.unlockcanvasandpost(canvas); } @override public void run() { while(true){ try{ mydraw(); thread.sleep(100); }catch(interruptedexception e){ e.printstacktrace(); } } } @suppresslint("clickableviewaccessibility") @override public boolean ontouchevent(motionevent event) { switch (event.getaction()) { case motionevent.action_down: // 按下 cx = (int) event.getx(); cy = (int) event.gety(); break; case motionevent.action_move: // 移动 cx = (int) event.getx(); cy = (int) event.gety(); break; case motionevent.action_up: // 抬起 cx = (int) event.getx(); cy = (int) event.gety(); break; } return true; } //surface创建的时候调用 @override public void surfacecreated(surfaceholder surfaceholder) { //获取屏幕高度 screenw = getwidth(); screenh = getheight(); thread.start(); } //surface被改变的时候调用 @override public void surfacechanged(surfaceholder surfaceholder, int i, int i1, int i2) { } //surface销毁的时候调用 @override public void surfacedestroyed(surfaceholder surfaceholder) { dorecycledifnot(mbitmap); } //回收一个未被回收的bitmap public static void dorecycledifnot(bitmap bitmap) { if (!bitmap.isrecycled()) { bitmap.recycle(); } } }
如对本文有疑问, 点击进行留言回复!!
Xamarin 安卓 相机 各种坑 目标API Android 6以后,我选的目标API版本是 Android 10
Android 9.0+软件某些功能突然暴毙:cleartext not permitted
Android : Resource is not a Drawable (color or path)
Flutter问题集锦——Android Studio 4.0.1 在AVD Manger中启动模拟器报“unable to locate abd”
网友评论