简体   繁体   English

保持Android ImageButton的宽高比

[英]Keep Android ImageButton aspect ratio

I've looked at previous questions on this topic and none of them seem to work. 我已经看过以前有关该主题的问题,但似乎都没有。 I have a horizontally oriented linearlayout with two (should-be) perfectly square ImageButtons in them. 我有一个水平定向的linearlayout,其中有两个(应该是)完全正方形的ImageButton。 The linearlayout successfully spans the width of the screen and the ImageButtons' widths are perfect; linearlayout成功地跨越了屏幕的宽度,ImageButton的宽度非常完美; however, they are rendered with twice the height that they should be. 但是,它们的渲染高度是其应有高度的两倍。 I have tried using the scaleTypes of fitStart and fitEnd as well as fitXY and they still render the same--as if they see the parent's width and use it to calculate their scaled height without taking into consideration the width of the other objects that are also in the linearlayout. 我尝试使用fitStart和fitEnd以及scaleXY的scaleTypes进行渲染,它们仍然呈现相同的效果-就像他们看到父级的宽度并使用它来计算其缩放高度时一样,不考虑其他也是在linearlayout中。 So I end up with two 2:1 aspect-ratio buttons next to each other with this code: 因此,我最终得到两个两个1:1的宽高比按钮,它们之间的代码如下:

<LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_margin="10dp"
        android:scaleY="1"
        android:orientation="horizontal"
        >

        <ImageButton
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/tapdat_tap2"
            android:scaleType="fitXY"/>

        <ImageButton
            android:id="@+id/button3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="0dp"
            android:layout_weight="1"
            android:background="@drawable/tapdat_nottap"
            android:scaleType="fitXY"/>

    </LinearLayout>

Additionally, I have tried putting a scaleY=".5" in the linearlayout tag and it renders with the correct height, however it leaves a large amount of unusable space where the excess height was cut out, which other content cannot fill. 另外,我尝试将scaleY =“。5”放入linearlayout标记中,并以正确的高度进行渲染,但是它留下了大量无法使用的空间,多余的高度被切掉,其他内容无法填充。 (I have also tried putting this scaleY on the ImageButtons individually with the same results.) (我也尝试过将scaleY分别放在ImageButtons上,结果相同。)

This is because you are not setting the height in any way and the ratio depends on the width. 这是因为您没有以任何方式设置高度,并且比率取决于宽度。

// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = layout.getWidth();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM