`

android 触摸点在屏幕中的坐标与bitmap在屏幕中坐标的比较

 
阅读更多

最近项目中要实现点击游戏主角附近位置,控制主角的运动,之前总是出现问题,触摸主角左上角时得到的坐标和主角位图在屏幕中的坐标不一致。

最终问题得到解决,一个原因是坐标系的选取是否都选取了屏幕坐标系,第二个原因是主角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 stub
			float 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;
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics