表面视图和缩放

Surface view and scaling

首先,我为我的英语道歉。

我是Android App编程的新手,最近发现了Canvas和Bitmap,所以我决定制作一个只能使用横向的"Game"。我也发现了 SurfaceView 以及如何在我的 SurfaceView 上实现背景,但首先是我的背景是一张 496x288 的图像。

我在互联网上搜索以了解如何很好地缩放以用背景和其他屏幕填充 phone 的所有屏幕。所以我找到这段代码并尝试在我的应用程序中使用。

@SuppressLint("WrongCall")
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.fondo1escalado);
            float scale = (float) background.getHeight() / (float) getHeight();
            int newWidth = Math.round((background.getWidth() / scale));
            int newHeight = Math.round(background.getHeight() / scale);
            scaled = Bitmap.createScaledBitmap(background, newWidth, newHeight, true);
            gameLoopThread.setRunning(true);
            gameLoopThread.start();


}

@SuppressLint("WrongCall")
protected void onDraw(Canvas canvas) {

    canvas.drawColor(Color.BLUE);
    canvas.drawBitmap(scaled, 0,0, null);
}

有效,但效果不佳。我明白了:

(人品不用担心)

它可以很好地缩放,但不能适应所有屏幕(见蓝色背景)。

所以,作为一个优秀的程序员,我尝试使用我设计的 GUI 来解决这个问题,它的尺寸是 296x912,我使用了相同的代码,它在所有屏幕上的高度都很好地缩放,但不是在宽度上甚至是平板电脑。

这是GUI的代码

float scalaInterfazAltura = (float) interfaz.getHeight() / (float) getHeight();
        int newHeightInterfaz = Math.round(interfaz.getHeight() / scalaInterfazAltura);
        int newWidthInterfaz = Math.round(interfaz.getWidth() / scalaInterfazAltura);
        scaledinterfaz = Bitmap.createScaledBitmap(interfaz, newWidthInterfaz, newHeightInterfaz, true);
        canvas.drawBitmap(scaledinterfaz, getWidth() - interfaz.getWidth()/2, 0, null);

所以,我的问题是:Surfaceview 中有一个东西可以很好地缩放吗?我做错了什么?

谢谢。

发生这种情况是因为您的显示高度大于视图高度。 尝试使用 surfaceView.getHeight() 而不是 interfaz.getHeight().

您也可以使用

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

在你的 Activity 之前 setContentView() 让你的游戏全屏显示。