2011-01-25 185 views
7

所以我需要根據屏幕區域改變圖像的大小。圖像必須是屏幕高度的一半,否則會重疊一些文字。Android根據屏幕大小更改圖像大小?

所以高度= 1/2屏幕高度。 寬度=身高*長寬比(只是試圖保持寬高比相同)

我發現的東西是:

Display myDisplay = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
int width =myDisplay.getWidth(); 
int height=myDisplay.getHeight(); 

但我將如何在Java中改變圖像高度?如果可能的話甚至是XML?我似乎無法找到可行的答案。

回答

17

您可以在代碼中使用LayoutParams。不幸的是,沒有辦法通過XML來指定百分比(不是直接的,你可以用權重來搞亂,但這並不總是有幫助,它不會保持你的寬高比),但這應該適用於你:

//assuming your layout is in a LinearLayout as its root 
LinearLayout layout = (LinearLayout)findViewById(R.id.rootlayout); 

ImageView image = new ImageView(this); 
image.setImageResource(R.drawable.image); 

int newHeight = getWindowManager().getDefaultDisplay().getHeight()/2; 
int orgWidth = image.getDrawable().getIntrinsicWidth(); 
int orgHeight = image.getDrawable().getIntrinsicHeight(); 

//double check my math, this should be right, though 
int newWidth = Math.floor((orgWidth * newHeight)/orgHeight); 

//Use RelativeLayout.LayoutParams if your parent is a RelativeLayout 
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    newWidth, newHeight); 
image.setLayoutParams(params); 
image.setScaleType(ImageView.ScaleType.CENTER_CROP); 
layout.addView(image); 

可能過於複雜,也許有一個更簡單的方法?不過,這是我第一次嘗試。

+0

看來我得到一個強制關閉,如果我試圖運行這個。如果這有所幫助,在LogCat下,我得到「未捕獲的處理程序:由於未捕獲的異常導致主線程退出」。我不確定這是什麼意思。 Ps.I'm有點新的Android仍然 – QQWW1 2011-01-25 21:00:39

相關問題