在 Android 如何设置矢量绘图大小

In Android how to set vector drawable size

我了解到 Add Multi-Density Vector Graphics 并且我只需要一个矢量 xml 图像文件即可支持所有屏幕尺寸。但是,当我尝试时,我仍然必须设置:

   <android.support.v7.widget.AppCompatImageView
                android:id="@+id/country_image"
                android:layout_width="50dp"
                android:layout_height="35dp"
                android:paddingTop="4dp">

android:layout_widthandroid:layout_height 喜欢上面的代码,使矢量具有我想要的大小。

在上面的代码中,AppCompatImageView 显示了一个矢量国旗图像,如果我没有设置宽度和高度,图像会占据屏幕。

这应该如何工作?

首先,简单地说,矢量图形文件包含如何绘制图像的规则。这些规则 与图像大小无关 。因此,您将对任何分辨率和任何尺寸使用相同的矢量文件,这就是为什么您只需要一个文件的原因。

其次,您需要 hdpixhdpi 和其他版本的 png 的原因是为了在具有不同像素密度的屏幕上显示您的图像。例如,您不需要大图像即可在具有 320x480 分辨率 的旧 phone 上显示它。所以 系统会选择你的 mdpi 或 ldpi png。但是,如果您的图像显示在 全高清屏幕 上,例如小 png 看起来像素化,所以 系统选择 xhdpixxhdpi png 版本。它无法从 ldpi 生成 xhdpi,因此您 需要不同的图像文件

另一方面,当您使用矢量图形时系统可以从同一个文件中创建任意分辨率的图像。它将为 320x480 屏幕创建一个小图像,为全高清屏幕创建一个大图像 - 因此您只需要 一个文件就可以控制所有这些!

回复您的评论:

您可以将 layout.xml 文件放在 res/drawable 中,它将用于所有屏幕。然后你在 dp 中设置大小。

dp or dip Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".

因此您将拥有一个布局文件,在其中设置图像的 layout_heightlayout_width 一次,它将在所有可能的屏幕上使用。