为什么在尝试使用 Android 使 png 跟随用户的手指时会得到偏移量?

问题描述

我试图让一个 png 图像跟随用户在屏幕上的手指,但是当它在屏幕上绘制时它以某种方式获得了偏移量。这是视图的运行代码

public float x,y;
public Dot dot;
public Paint paint;

public MainView(Context context)
{
    super(context);
    this.dot = new Dot(getResources());
    this.paint = new Paint();
    this.setonTouchListener(this);
}

@Override
public boolean onTouch(View view,MotionEvent motionEvent) {
    switch (motionEvent.getAction())
    {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            this.x = motionEvent.getX();
            this.y = motionEvent.getY();
            this.update();
            break;
    }
    return true;
}

public void update()
{
    if(dot.setPosition(x,y))
    {
        Log.e("MainView",String.valueOf(x) + " ; " + String.valueOf(y));
        // Position has changed
        if(getHolder().getSurface().isValid())
        {
            Canvas canvas = getHolder().lockCanvas();
            canvas.drawColor(Color.CYAN);
            canvas.drawBitmap(dot.bm,dot.pos.get(0),dot.pos.get(1),paint);
            getHolder().unlockCanvasAndPost(canvas);
        }
    }
}

对于点:

public Bitmap bm;
public ArrayList<Float> pos;

public Dot(Resources res)
{
    bm = BitmapFactory.decodeResource(res,R.drawable.dot);
    pos = new ArrayList<>(2);
    pos.add((float) 0);
    pos.add((float) 0);
}

public boolean setPosition(float x,float y)
{
    if(x != pos.get(0) || y != pos.get(1))
    {
        pos.set(0,x);
        pos.set(1,y);
        return true;
    }
    return false;
}

结果如下:

First image Second image

我不确定问题出在哪里,我使用的是小米 Poco X3 NFC

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)