gpt4 book ai didi

android - 如何使 MotionEvent 的坐标与缩放 Canvas 的坐标相匹配?

转载 作者:行者123 更新时间:2023-11-29 14:13:34 25 4
gpt4 key购买 nike

我有一个 Canvas这是按比例缩放的,所以一切都更合适:

@Override
public void draw(Canvas c){
super.draw(c);
final float scaleFactorX = getWidth()/(WIDTH*1.f);
final float scaleFactorY = getHeight()/(HEIGHT*1.f);

if(c!=null) {
final int savedState = c.save();

c.scale(scaleFactorX, scaleFactorY);

(rendering)

c.restoreToCount(savedState);
}

}

它基于这两个缩放:

public  static final int WIDTH = 856;
public static final int HEIGHT = 1050;

这导致处理触摸事件的 MotionEvent 的坐标不等于使用 Canvas 创建的坐标的问题。当我尝试检查 MotionEvent Rect 和基于渲染比例的类的 Rect 之间的碰撞时,这会导致问题。这导致类 SuperCoin 的 X 坐标不等于 MotionEvent X 坐标。通常,MotionEvent 的坐标 X 和 Y 都比屏幕的最大尺寸大得多(由 WIDTHHEIGHT 定义)

 @Override
public boolean onTouchEvent(MotionEvent e) {
super.onTouchEvent(e);

switch (MotionEventCompat.getActionMasked(e)) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
(...)
Rect r = new Rect((int)e.getX(), (int)e.getY(), (int)e.getX() + 3, (int)e.getY() + 3);
if(superCoins.size() != 0) {
for (SuperCoin sc : superCoins) {
if (sc.checkCollision(r)) {
progress++;
superCoins.remove(sc);
}
}
}

break;

}

return true;

}

还有 super 币:

public class SuperCoin {
private Bitmap bm;
public int x, y, orgY;
Clicker cl;
private Long startTime;
Random r = new Random();
public SuperCoin(Bitmap bm, int x, int y, Clicker c){
this.x = x;
this.y = y;
this.orgY = y;
this.bm = bm;
this.cl = c;
startTime = System.nanoTime();
bounds = new Rect(x, y, x + bm.getWidth(), y + bm.getHeight());

}

private Rect bounds;

public boolean checkCollision(Rect second){
if(second.intersect(bounds)){
return true;
}
return false;
}


private int velX = 0, velY = 0;


public void render(Canvas c){

long elapsed = (System.nanoTime()-startTime)/1000000;
if(elapsed>50) {


int cx;
cx = r.nextInt(2);
if(cx == 0){
velX = r.nextInt(4);
}else if(cx == 1){
velX = -r.nextInt(4);
}

velY = r.nextInt(10) + 1;

startTime = System.nanoTime();
}

if(x < 0) velX = +2;
if(x > Clicker.WIDTH) velX = -2;

x += velX;
y -= velY;


c.drawBitmap(bm, x, y, null);
}
}

当 MotionEvent X 坐标大于屏幕缩放的最大坐标时,如何检查两者之间的碰撞?

老实说,我不完全确定为什么在 SuperCoin 类中定义的 Rect 与在 onTouchEvent 方法中定义的不同。我猜是因为 MotionEvent 定义的 X 和 Y 与缩放 Canvas 定义的 X 和 Y 永远不同。 SuperCoin 类中的 Rect 以它所传递的位图的宽度为准。它根据位图的宽度和高度对其进行缩放。

最佳答案

在过去 2 天通过 StackOverflow 和 Google 寻找接近解决方案的东西后,我想到了这个:在 android 中放大/缩小或拖动后获取 Canvas 坐标这解决了问题。真的很难找到,因为标题有点误导(另一个问题)

float px = e.getX() / mScaleFactorX;
float py = e.getY() / mScaleFactorY;
int ipy = (int) py;
int ipx = (int) px;
Rect r = new Rect(ipx, ipy, ipx+2, ipy+2);

我将其添加为答案并接受它,因此它不再是 Unresolved 问题,因为它已经解决了。上面的代码将坐标转换为整数,因此它们可用于检查手指和我正在检查的对象之间的碰撞

关于android - 如何使 MotionEvent 的坐标与缩放 Canvas 的坐标相匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38061734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com