Android Drawable 图片大小设置方法 - 代码实现及 XML 配置
Android Drawable 图片大小设置方法 - 代码实现及 XML 配置
在 Android 开发中,您可能需要根据需要调整 Drawable 图片的大小。本文将介绍两种常用方法,分别通过代码和 XML 配置实现图片尺寸的控制。
1. 通过代码设置 bounds 属性
Android Drawable 的 bounds 属性是一个矩形,用来指定 Drawable 的大小和位置。您可以通过调用 Drawable 的 setBounds() 方法设置其大小和位置。
例如,以下代码将一个 Drawable 对象的大小设置为宽为 100dp,高为 150dp:
Drawable drawable = getResources().getDrawable(R.drawable.icon);
int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources().getDisplayMetrics());
drawable.setBounds(0, 0, width, height);
2. 通过设置宽高属性
您也可以通过设置 android:width 和 android:height 属性来指定 Drawable 的宽度和高度。
例如,以下代码将一个 Drawable 对象的宽度设置为 100dp,高度设置为 150dp:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:width="100dp"
android:height="150dp">
<solid android:color="#FF0000" />
</shape>
总结
通过以上两种方法,您可以根据需要灵活控制 Android Drawable 图片的大小。选择哪种方法取决于您的具体需求和开发习惯。
原文地址: https://www.cveoy.top/t/topic/oYBr 著作权归作者所有。请勿转载和采集!