8

我的 Android 应用程序(基于文本的游戏)大量使用背景图像以提供更好的视觉氛围。例如,如果游戏中的动作将您带入酒馆,那么您将获得游戏中酒馆的背景图像。在图形上,这是一个巨大的改进,相对于你本来会得到的无聊的黑色背景。

然而,这也是一个问题,因为 android:background 总是延伸到屏幕的尺寸。结果是,如果玩家在纵向和横向模式之间切换,背景图像看起来很糟糕。更糟糕的是,许多设备具有非常不同的纵横比(例如,320x480 mdpi、480x800 hdpi 和 480x852 hdpi),而且还会出现更多变化。

其他人如何解决这个问题?为主要分辨率/方向设置单独的图像对我来说不是一个选择,因为这会导致 apk 变得太大。

4

3 回答 3

5

第一步是获取设备本身的屏幕高度和宽度,然后根据需要拉伸/收缩或填充位图。这个SO 答案的来源应该有所帮助,复制如下。向约瑟夫提供原始答案的道具。

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
}
于 2010-09-03T12:30:44.617 回答
2

我建议您获取当前视图的宽度和高度。现在我不确定哪些函数会给你这些值,但我相信这是可能的。然后,您可以计算纵横比。我会将图像设置为 1000x1000 并只显示图像的某个部分,这样纵横比就不会出错。
我的相机也有同样的问题。所以我的解决方案是选择固定的宽度或高度这两个值之一,并根据纵横比计算正确的另一个值。我不确定是否已经有功能只显示图像的一部分,但我相信你可以写一些东西来复制图像的一部分并显示那部分。

缺点当然是您将只显示背景的一部分。由于手机的一般纵横比介于 1:1.3 和 1:1.8 之间,我想这不会是一个太大的问题。我宁愿以正确的方式看到图像的一部分,而不是看一个丑陋的拉伸图像。

于 2010-09-03T11:50:09.010 回答
2

也许您可以将背景图像创建为NinePatch图像,以便更好地控制它的拉伸方式?

否则,您可以通过设置scaleType属性来防止图像拉伸(或至少保持正确的纵横比),例如android:scaleType="center".

于 2010-09-03T12:30:39.430 回答