我正在为Android开发2D游戏,主要是我作为一种经验来学习Android应用程序的编程内幕,因此自然而然地会遇到很多难题。当前,我的主要活动实例化一个自定义类,该类扩展了SurfaceView并实现了SurfaceHolder.Callback。该视图实例化一个线程,该线程处理大多数逻辑和所有图形处理(包括实例化画布并对其进行绘制等)。

好吧,由于我是一个初学者,所以我开始设计画布时要比屏幕大得多,并允许用户滚动查看画布的所有部分,但我没有想到...但是,那是我的意思需要发生。

如果有简便的方法,请告诉我。

我最好的猜测是将画布的实际创建放在一个单独的类中,该类扩展了ScrollView,并以某种方式只是从我的线程中对该画布调用所有Draw()。这可能吗?我的点击事件实际上是从主要活动中捕获的(仅供参考)。

最佳答案

最好的选择是使用“摄影机”翻译画布。做这样的事情:

// Creates a new camera object
Camera mCam = new Camera();
float startX;
float startY;

@Override
public void onTouch(MotionEvent event)
{
    if(event.getAction() == MotionEvent.ACTION_DOWN)
    {
        startX = event.getX();
        startY = event.getY();
    }
    else if(event.getAction() == MotionEvent.ACTION_MOVE)
    {
        float x = event.getX();
        float y = event.getY();

        // Lets you translate the camera by the difference
        mCam.translate(x -startX, startY - y, 0.f);
        startX = event.getX();
        startY = event.getY();
    }
}

@Override
public void onDraw(Canvas canvas)
{
    // Draw here the objects you want static in the background
    canvas.drawBitmap(mBackground, 0, 0, null);

    canvas.save();
    mCam.applyToCanvas();

    // Draw here the objects you want to move
    canvas.drawBitmap(mBall, 0, 0, null);

    canvas.restore();

    // Draw here the objects you want static on the forebround
    canvas.drawBitmap(mScore, 0, 0, null);
}


请注意,您正在以0,0绘制mBall,但由于摄像机平移,它将移动指定的量。我希望这有帮助。玩得开心 :)

关于java - 使我的 Canvas 可滚动,而无需大修,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6393672/

10-11 22:15
查看更多