如何才能在android中的图像按钮上正确保持宽高比?

时间:2011-11-01 02:35:28

标签: android aspect-ratio

  

可能重复:
  how do i keep the aspect ratio on image buttons in android?

我有5个方形骰子,因为图像按钮排列在我的布局底部附近。我希望他们占据整个布局的宽度,但我似乎无法让他们正确地保持宽高比,同时占用整个宽度。 目前我的代码如下:

 <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:layout_margin="1dp"
        android:layout_gravity="bottom" 
        > 
        <ImageButton
             android:id="@+id/die1" 
             android:layout_width="fill_parent"
             android:layout_height="wrap_content" 
             android:layout_gravity="center"
             android:adjustViewBounds="true"
             android:layout_weight="1"
             android:layout_margin="2dp"
             android:scaleType="centerInside"
             />  
        <ImageButton
             android:id="@+id/die2" 
             android:layout_width="fill_parent"
             android:layout_height="wrap_content" 
             android:layout_gravity="center"
             android:adjustViewBounds="true"
             android:layout_weight="1"
             android:layout_margin="2dp"
             android:scaleType="centerInside"
             /> .....

看起来像这样: 60dp

如果我不包括

android:layout_height="60dp"
然后骰子变得歪斜,看起来像这样:skewed

然而,当我尝试在平板设备上显示或高分辨率的东西时,出现“60dp”部分的问题就出现了这样的问题:

enter image description here

我哪里错了?!

3 个答案:

答案 0 :(得分:3)

你将不得不做两件事之一:

1)提供骰子图像的ldpi,mdpi,hdpi和x-hdpi版本。将它们放在各自的drawable文件夹中,android将负责其余部分。 了解如何:http://developer.android.com/guide/practices/screens_support.html

或者

2)获取屏幕大小并手动设置imageview大小java。您可以使用以下方式获取屏幕尺寸:

 Display d = ((android.view.WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
 screenWidth = d.getWidth();

剩下的由你决定。祝你好运!

CNC中 设置ImageView(或任何其他View的Java大小)

 myHeight = screenSize/5; //These are in pixels not dp's
 myWidth = screenSize/5;
 LinearLayout.LayoutParams myLayoutParams = 
               new LinearLayout.LayoutParams(myWidth,myHeight);
 myView.setLayoutParams(myLayoutParams);

希望它的表现很好。

答案 1 :(得分:0)

<强>尝试

 android:layout_height="wrap_content"
   

&安培;

<LinearLayout> attribite android:layout_height="60dp"替换为android:layout_height="wrap_content"

答案 2 :(得分:0)

将ImageButtons的宽度设置为fill_parent,并将scaletype fitStart用于拥抱左边距的图像,将fitEnd用于右边的图像。应该这样做,至少就你的示例图像而言。如果图像的比例宽度超出屏幕宽度,则可能会出现间距问题,但它应该适合您。