【问题标题】:Android ImageButton made too big by it's image in backgroundAndroid ImageButton 因背景中的图像而变得太大
【发布时间】:2012-10-19 17:29:57
【问题描述】:

我正在将图像动态加载到屏幕上的图像按钮。图像不会提前知道,并且大小不同。

有谁知道如何确保图像按钮的大小不受分配给它的任何图像的影响。最好拉伸图像以适合按钮。我尝试使用 android:scaleType="fitXY" 并将 ewidth 和 height 设置为硬值(不推荐)。无论我做什么,图像都决定了按钮的大小,反之亦然!救命!

我尝试了以下组合。图片随机来自互联网搜索。

                    <ImageButton
                        android:id="@+id/ImageButton1"
                        android:layout_height="93px"
                        android:src="@drawable/image1"
                        android:layout_width="93px"
                        android:background="93px" />
                    <ImageButton
                        android:id="@+id/ImageButton4"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/image1"
                        android:scaleType="fitXY" />

非常感谢任何帮助!

【问题讨论】:

    标签: java android imagebutton


    【解决方案1】:

    不要设置每个 ImageButton 的大小,而是将按钮放在容器布局中并设置容器的大小。例如:

    <LinearLayout
            android:id="@+id/container"
            android:layout_width="80dp"
            android:layout_height="80dp" >
    
            <ImageButton
                android:id="@+id/ImageButton1"
                android:src="@drawable/image1"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:scaleType="fitXY" />
    </LinearLayout>
    

    这应该会强制您的图像按钮不大于其所在容器的大小。

    【讨论】:

    • 这将有助于确保图像按钮的大小对于设备的屏幕大小/密度保持正确。谢谢我试一试。
    • 我尝试了这种方法,高度部分采用但宽度没有改变 - 我使用了与您的示例相同的布局。有什么想法吗?
    • 为你的图片添加 android:scaleType="fitXY" 属性。
    【解决方案2】:

    您拥有的位图大小不同。所有这些都可以转换为可能适合您的应用程序的 newHeight 和 newWidth。所以现在大小将保持不变。使用下面的代码使其具有合适的宽度和高度

    Bitmap yourBitmap;
    Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
    

    【讨论】:

    • 谢谢我试一试。我希望我的 imagebutton 大小根据设备显示密度/大小的大小而改变 - 我是否需要通过根据屏幕大小设置我的 imagebuttons 大小来做到这一点?
    • 是的,根据您可以通过 getHeight() 和 getWidth() 方法获得的设备大小,您可以根据自己的需要决定您的图像大小
    • 这似乎将按钮内的图像设置为合适的大小,但灰色按钮的大小仍然相同。我应该在按钮本身上使用一些方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2016-05-06
    • 1970-01-01
    • 2023-04-03
    • 2016-08-26
    • 2012-07-22
    • 2014-11-18
    相关资源
    最近更新 更多