为什么我在我的 Android 应用中使用的可绘制对象在用作按钮背景时纵横比错误

Why drawables I use in my Android app have wrong aspect ratio when used as buttons background

我在 Android 应用程序布局中放置了一些图标。

它们是通过 "new vector asset" 命令从 material 设计 Google 集合的 svg 文件中导入的:https://material.io/resources/icons/?style=baseline

这是资源xml:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
 <path
  android:fillColor="#FF000000"
  android:pathData="M13,7h-2v4L7,11v2h4v4h2v-4h4v-2h-4L13,7zM12,2C6.49,2 2,6.49 2,12s4.49,10 10,10 10,-4.49 10,-10S17.51,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8z"/>
</vector>

它们用作按钮的背景:

<Button
        android:id="@+id/duplicate_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/duplicate_icon"
        />

但是结果并不好,因为我得到了这样的结果:

应该是正方形,但我得到的是矩形。 svg 文件在其他应用程序中显示时具有正确的比例。

三个按钮呈线性布局:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

并且有一个容器:

<LinearLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:border="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ItemDetailFragment">

里面还有一些其他的东西。

我的代码有什么问题?

使用 wrap_content 作为按钮的宽度和高度对您没有帮助,因为您将图像设置为背景,它不是按钮的实际内容。您需要为按钮指定固定尺寸。根据您的设计,我建议您查看 ImageButton 或像这样简单地使用 ImageView

<!-- ?attr/selectableItemBackground is for button effects -->
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?attr/selectableItemBackground" 
    android:src="@drawable/duplicate_icon" />

似乎 "wrap_content" 没有默认为您想要的 24dp,因为可绘制对象实际上不是您按钮的内容,而只是它的背景。您可以将按钮的大小明确设置为 24dp,如下所示:

布局:

<Button
android:id="@+id/duplicate_button"
android:layout_width="@dimen/my_button_size"
android:layout_height="@dimen/my_button_size"
android:background="@drawable/duplicate_icon"
/>

可绘制:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="@dimen/my_button_size"
android:height="@dimen/my_button_size"
android:viewportWidth="@dimen/my_button_size"
android:viewportHeight="@dimen/my_button_size">

res/values/dimen.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="my_button_size">24dp</dimen>
</resources>