2012-09-29 72 views
3

我有一個TextView我在drawableLeft調整圖片大小爲根據textivew大小

<TextView 
    android:id="@+id/imgChooseImage" 
    android:layout_width="fill_parent" 
    android:layout_height="0dp" 
    android:layout_weight="3" 
    android:background="@drawable/slim_spinner_normal" 
    android:drawableLeft="@drawable/ic_launcher"/> 

設定圖像和我只想知道我應該在java代碼編寫動態替換新的圖像,該圖像不能超過TextView並且在可繪製的左側圖像中看圖像良好。

scalefactor需要使用什麼?下面

int scaleFactor = Math.min(); 

是java代碼

BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
// If set to true, the decoder will return null (no bitmap), but 
// the out... fields will still be set, allowing the caller to 
// query the bitmap without having to allocate the memory for 
// its pixels. 
bmOptions.inJustDecodeBounds = true; 
int photoW = hListView.getWidth(); 
int photoH = hListView.getHeight(); 

// Determine how much to scale down the image 
int scaleFactor = Math.min(photoW/100, photoH/100); 

// Decode the image file into a Bitmap sized to fill the View 
bmOptions.inJustDecodeBounds = false; 
bmOptions.inSampleSize = scaleFactor; 
bmOptions.inPurgeable = true; 
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), Const.template[arg2],bmOptions); 

Drawable draw = new BitmapDrawable(getResources(), bitmap); 

/* place image to textview */ 
TextView txtView = (TextView) findViewById(R.id.imgChooseImage); 
txtView.setCompoundDrawablesWithIntrinsicBounds(draw, null,null, null); 
position = arg2; 

回答

0

您所要求的一種方式來計算TextView的確切高度的佈局後,讓你可以爲drawableLeft屬性調整位圖的大小。 這個問題是由幾個問題複合:

  1. 如果文本包裝到多行高度可以顯着改變。
  2. 根據設備硬件屏幕密度,位圖的渲染大小 將計算時,可以改變, 位圖在縮放/渲染的確切大小,因此屏幕密度的irregardless將已經採取 來考慮scaleFactor
  3. 最後,scaleFactor不提供確切大小的圖像請求。 它只將位圖的大小限制爲儘可能小的圖像 ,它仍然與您的請求相同或更大,以節省 內存。您仍然需要將圖像調整到您計算的確切高度 。

drawableLeft方法不能克服上述問題,我認爲這是一個更好的辦法,而不必使用Java代碼來調整,以達到您的預期佈局。

我相信你應該將TextView替換爲水平方向的LinearLayout,其中包含ImageViewTextView。 TextView的高度設置爲"WRAP_CONTENT",並設置ImageView的到「中心」的scaleType,就像這樣:

android:scaleType="center" 

的的LinearLayout將在TextView的文本的高度和的ImageView scaleType將迫使位圖在佈局過程中自動調整大小。這裏可用scaleTypes的參考:ImageView.ScaleType

當然,您將不得不調整LinearLayout,ImageView和TextView的XML佈局參數,使其以所需的確切方式居中,對齊和定向。但是,至少你只會做一次。

由於看起來您將從應用程序資源中將照片加載到ImageView中,因此您可能知道該圖像不是很大,因此您可以直接打開該位圖,或使用​​。否則,如果圖像特別大或您得到異常,則計算scaleFactor如下:

int inSampleSize = 1; 
if (height > reqHeight || width > reqWidth) { 
    if (width > height) { 
     inSampleSize = Math.round((float) height/(float) reqHeight); 
    } else { 
     inSampleSize = Math.round((float) width/(float) reqWidth); 
    } 
}