简体   繁体   中英

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. The linearlayout successfully spans the width of the screen and the ImageButtons' widths are perfect; 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. So I end up with two 2:1 aspect-ratio buttons next to each other with this code:

<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. (I have also tried putting this scaleY on the ImageButtons individually with the same results.)

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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