android 触摸点在屏幕中的坐标与bitmap在屏幕中坐标的比较
16lz
2021-01-26
最近项目中要实现点击游戏主角附近位置,控制主角的运动,之前总是出现问题,触摸主角左上角时得到的坐标和主角位图在屏幕中的坐标不一致。
最终问题得到解决,一个原因是坐标系的选取是否都选取了屏幕坐标系,第二个原因是主角bitmap在屏幕中的坐标跟屏幕的density 有关。
density = android中图片宽:pc中图片宽 = 1.5
event.getRawY()//得到触摸点在屏幕中的坐标
private void drawImage(Canvas canvas, int x, int y,Bitmap bsrc, int sx, int sy, int w, int h) {Rect rect_src = new Rect();rect_src.left = sx;rect_src.right = sx + w;rect_src.top = sy;rect_src.bottom = sy + h;Rect rect_dst = new Rect();rect_dst.left = x;rect_dst.right = x + w;rect_dst.top = y;rect_dst.bottom = y + h;canvas.drawBitmap(bsrc, rect_src, rect_dst, null);rect_src = null;rect_dst = null;}//This function ignores the density associated with the bitmap. This is because the source and destination rectangle coordinate spaces are in their respective densities, so must already have the appropriate scaling factor applied.
最终解决方案:
public boolean onTouchEvent(MotionEvent event) {if (event.getAction() == MotionEvent.ACTION_DOWN) {// TODO Auto-generated method stubfloat y = event.getRawY()*3/2;float x = event.getRawX()*3/2;touch_y = y;touch_x = x;// 按ship上方if ((int) y < (Ship.ship_screen_ypos)) {Ship.changeShipState(1);Ship.ship_screen_ypos -= Ship.ship_height;} else if ((int) y > Ship.ship_screen_ypos+Ship.ship_height) {// 按ship下方Ship.changeShipState(2);Ship.ship_screen_ypos += Ship.ship_height;}if((int)x>(Ship.ship_screen_xpos+Ship.ship_width)){// 加速ConstantUtil.SPEED+=5;}else if((int)x<Ship.ship_screen_xpos){// 减速ConstantUtil.SPEED-=5;}}return true;}
更多相关文章
- Android保持屏幕常亮的两种方法
- Android-UI屏幕适配全攻略
- android屏幕适配,除了使用dp,还可以使用比例
- android dp sp px区别,android获取屏幕尺寸、密度
- 仅仅是个人记录:Android(安卓)的机型适配: 屏幕适配(包括dpi,dp,sp
- android中屏幕适配的方式
- Android高清输出四大名“捕”
- 入手 Nexus S
- 【Android游戏开发二十二】(图文详解)游戏中灵活实现动画播放!