2010-09-03 72 views
8

我的Android應用程序(基於文本的遊戲)使用很多背景圖像以提供更好的視覺氛圍。例如,如果遊戲中的動作將你帶入酒館,那麼你會在遊戲中獲得一個酒館的背景圖像。這是一個巨大的改進,用圖形的方式說明,否則你會得到無聊的黑色背景。在Android中處理背景圖像的不同屏幕分辨率

然而,這也是一個問題,因爲android:background總是拉伸到屏幕的尺寸。結果是如果玩家在縱向模式和橫向模式之間切換,背景圖像看起來非常糟糕。更糟糕的是,許多設備的縱橫比非常不同(例如,320x480 mdpi,480x800 hdpi和480x852 hdpi),甚至還會有更多變化。

其他人如何解決這個問題?對於主分辨率/方向有單獨的圖像對我來說不是一種選擇,因爲這會導致apk變得太大。

+0

感謝您的答案。對不起,我只能選中其中一個。 :) – 2010-09-05 21:47:25

+0

羅曼提供了另一個有用的答案http://stackoverflow.com/questions/3944080/android-avoid-scaling-of-background – 2010-10-29 10:17:03

回答

2

我建議你得到你當前視圖的寬度和高度。現在我不確定哪些功能會給你這些值,但我相信這是可能的。然後,您可以計算縱橫比。我會讓圖像像1000x1000一樣,只顯示圖像的某個部分,以便縱橫比不會出錯。
我有與相機相同的問題。所以我的解決方案是選擇固定的兩個值中的一個,即寬度或高度,並根據縱橫比計算正確的其他值。我不確定是否有函數只顯示圖像的一部分,但我相信你可以寫一些東西來複製圖像的一部分並顯示該部分。

缺點是當然你只會顯示背景的一部分。由於手機的總縱橫比在1:1.3和1:1.8之間,我猜這不會是一個太大的問題。我寧願以正確的方式看到圖像的一部分,而不是看一張醜陋的拉伸圖像。

2

也許你可以創建你的背景圖像作爲NinePatch圖像,這樣你就可以更好地控制它如何延伸?

否則,你可以防止圖像拉伸(或至少保持正確的縱橫比)通過設置scaleType屬性如android:scaleType="center"

5

的第一步是獲得裝置本身的屏幕的高度和寬度,然後伸展/根據需要縮小或墊的位圖。這SO answer有源應該幫助,複製下面。原始答案的道具爲Josef

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

以下是獲取方向的一般資源。

int orientation = display.getOrientation(); 

here一些更復雜的源(有點混亂,但看起來是正確的)。

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 
}