在Android中处理不同屏幕分辨率的背景图像

8
我的Android应用程序(一个基于文本的游戏)在很多情况下使用背景图片,以提供更好的视觉氛围。例如,如果游戏中的动作带你进入一家酒馆,那么你会在游戏中得到一张酒馆的背景图片。这在图形上是一个巨大的改进,比起无聊的黑色背景要好得多。
然而,这也是一个问题,因为android:background总是会被拉伸到屏幕的尺寸。结果是如果玩家在纵向和横向模式之间切换,背景图片看起来非常糟糕。更糟糕的是,许多设备具有非常不同的宽高比(例如320x480 mdpi,480x800 hdpi和480x852 hdpi),并且还有更多的变化。
其他人是如何解决这个问题的呢?对我来说,为主要分辨率/方向单独制作图像不是一个选择,因为这将导致apk变得太大。

谢谢回答。很抱歉我只能选择其中一个人。 :) - Michael A.
Romain在https://dev59.com/Rm865IYBdhLWcg3wLrhE中提供了另一个有用的答案。 - Michael A.
3个回答

5

第一步是获取设备本身的屏幕高度和宽度,然后根据需要拉伸/缩小或填充您的位图。这个SO答案提供了源代码,可以帮助您,如下所示。感谢Josef原始答案。

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();

以下是有关获取方向的通用源代码。

int orientation = display.getOrientation(); 

或者从这里获取更复杂的源代码(有点混乱,但看起来是正确的)。

public int getscrOrientation()
{
  Display getOrient = getWindowManager().getDefaultDisplay();

  int orientation = getOrient.getOrientation();

  // Sometimes you may get undefined orientation Value is 0
  // simple logic solves the problem compare the screen
  // X,Y Co-ordinates and determine the Orientation in such cases
  if(orientation==Configuration.ORIENTATION_UNDEFINED){

      Configuration config = getResources().getConfiguration();
      orientation = config.orientation;

      if(orientation==Configuration.ORIENTATION_UNDEFINED){
        //if height and widht of screen are equal then
        // it is square orientation
            if(getOrient.getWidth()==getOrient.getHeight()){
            orientation = Configuration.ORIENTATION_SQUARE;
            }else{ //if widht is less than height than it is portrait
      
                if(getOrient.getWidth() < getOrient.getHeight()){
                orientation = Configuration.ORIENTATION_PORTRAIT;
                }else{ // if it is not any of the above it will defineitly be landscape
                orientation = Configuration.ORIENTATION_LANDSCAPE;
                }
            }
       }
  }
  return orientation; // return value 1 is portrait and 2 is Landscape Mode
}

2
我建议您获取当前视图的宽度和高度。目前我不确定哪些函数会给您这些值,但我相信这是可能的。有了这个,您可以计算出一个纵横比。我会将图片设置为1000x1000,并只显示一部分图片,以便纵横比不会出错。
我在摄像头上也遇到了同样的问题。所以我的解决方案是选择其中一个值,宽度或高度作为固定值,并根据纵横比计算出正确的另一个值。我不确定是否已经有函数可以只显示图像的一部分,但我相信您可以编写一些代码来复制图像的一部分并显示该部分。
缺点当然是您将只显示背景的一部分。由于手机的一般纵横比介于1:1.3和1:1.8之间,我想这不会是一个太大的问题。对我来说,我宁愿以正确的方式查看图像的一部分,而不是看着一个难看的拉伸图像。

2
也许您可以将背景图像创建为NinePatch图像,以便更好地控制其拉伸方式?
否则,您可以通过设置scaleType属性(例如android:scaleType="center")来防止图像被拉伸(或至少保持正确的长宽比)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接