Android:如何调整LinearLayout内TextView中的Drawable图片大小?
解决TextView中Compound Drawable尺寸调整问题
兄弟,我太懂你那种用了方法却没生效的憋屈了!setCompoundDrawablesWithIntrinsicBounds本身是按图片固有尺寸来设置的,直接传资源ID自然不会缩小图片——得先把Drawable缩放到目标尺寸再绑定给TextView才行。下面给你两种靠谱的解决方案:
方案一:通过代码手动缩放Drawable
这种方式适合需要动态调整尺寸的场景,核心思路是先获取原始Drawable,修改它的边界尺寸后再设置给TextView:
Kotlin 示例
val headingTextView = findViewById<TextView>(R.id.heading) val originalDrawable = ContextCompat.getDrawable(this, R.drawable.android_logo)?.mutate() originalDrawable?.let { // 把目标尺寸转换成DP对应的像素值,这里设置为40dp×40dp val targetSize = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 40f, resources.displayMetrics ).toInt() // 重新设置Drawable的显示边界 it.setBounds(0, 0, targetSize, targetSize) // 绑定到TextView的左侧(兼容RTL布局用setCompoundDrawablesRelative) headingTextView.setCompoundDrawables(it, null, null, null) }
Java 示例
TextView headingTextView = findViewById(R.id.heading); Drawable originalDrawable = ContextCompat.getDrawable(this, R.drawable.android_logo); if (originalDrawable != null) { int targetSize = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics() ); // 转换成Bitmap后缩放 Bitmap bitmap = ((BitmapDrawable) originalDrawable).getBitmap(); Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, targetSize, targetSize, true); Drawable scaledDrawable = new BitmapDrawable(getResources(), scaledBitmap); headingTextView.setCompoundDrawables(scaledDrawable, null, null, null); }
方案二:用XML定义缩放后的Drawable(更优雅)
如果不需要动态调整,直接用XML定义缩放后的Drawable是最省心的,不用写任何代码:
- 在
drawable文件夹下创建scaled_android_logo.xml:
<!-- 按比例缩放 --> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/android_logo" android:scaleWidth="0.5" <!-- 0.5表示缩小到原图的50% --> android:scaleHeight="0.5" android:gravity="center" />
或者直接指定固定尺寸:
<!-- 固定尺寸缩放 --> <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/android_logo" android:width="40dp" android:height="40dp" android:gravity="center" />
- 在TextView中直接引用这个XML文件:
<TextView android:id="@+id/heading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/scaled_android_logo" android:drawableStart="@drawable/scaled_android_logo" android:gravity="top" android:padding="8dp" />
为什么你之前的尝试没成功?
setCompoundDrawablesWithIntrinsicBounds(R.drawable.android_logo, 0, 0, 0)这种写法,只是告诉系统加载这个Drawable,并使用它的固有原始尺寸来设置边界,并没有做任何缩放操作——所以看起来和直接在XML里设置没区别,自然看不到缩小效果。
如果还是有问题,可以检查下TextView的padding、布局宽度是否限制了图片显示,或者有没有其他样式覆盖了你的设置~
内容的提问来源于stack exchange,提问作者Stu_Dent
相关产品推荐
相关产品推荐

