按钮拉伸的背景图像

Background image for button getting stretched

在我的布局中,我有一个带有背景图片的按钮。当我将宽度和高度都设置为 wrap_content 时,背景会被拉伸。但是当我对 dp 使用相同的值来设置宽度和高度时,我得到了预期的结果。为什么会这样?

图片原为圆形

           <Button
            android:id="@+id/captureButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:background="@drawable/custom_capture" />

设置为按高度和宽度包装内容时

当高度和宽度设置为 80dp 时

因为background是用来装满容器的。
但是,由于 Button 继承自 TextView,您可以使用 复合可绘制对象

大概是这样:

<Button
    android:id="@+id/captureButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:drawableLeft="@drawable/custom_capture"
/>

备选方案:使用 TextView

<TextView
    android:id="@+id/captureButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:drawableLeft="@drawable/custom_capture"
    android:clickable="true"
/>

使用上面的 xml 按钮布局,您将有一个带有空文本 ("") 的按钮,您应该注意到按钮的默认左右填充与顶部不同和底部。 因此,带有空文本的 Button 将具有矩形形状,而不是正方形,因此背景将被拉伸。

在您固定宽度和高度的情况下,它将确保按钮始终是您想要的大小(正方形),因此背景将完美显示。

您可以使用 9patch 或为您的按钮设置固定的宽度和高度