在Android的TextView中调整可绘制图像的大小

7

想知道如何在 LinearLayout 中的 TextView XML 中调整图片大小。我看到一些解决方案使用 setCompoundDrawablesWithIntrinsicBounds 方法,但我无法正确实现。

这是图片:

enter image description here

我想要缩小标志的大小。

这是我的 TextView 代码:

<TextView  
    android:id="@+id/heading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/android_logo"
    android:drawableStart="@drawable/android_logo"
    android:gravity="top"
    android:padding="16dp"
    android:singleLine="true"
    android:text="@string/heading"
    android:textSize="20dp"
    android:drawablePadding="5dp"/>
3个回答

27

尝试:

 android:scaleX="0.7"
 android:scaleY="0.7"

或者

将您的资源包装在一个可绘制对象中,该可绘制对象定义了您期望的大小,类似于:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

  <item
      android:drawable="@drawable/icon"
      android:width="@dimen/icon_size"
      android:height="@dimen/icon_size"
      />

</layer-list >

然后将其用于左侧drawable。


4
第二个建议适用于带有图像的TextView。感谢解决方案! - Stu_Dent
@PattyPutty 很高兴能帮到你 :) 祝你编程愉快 :) - Vidhi Dave
5
请注意,在 Android 6.0 之前的版本中,“width”和“height”项目属性无效。 - Zmiter

3

有唯一的解决方案,即使用Imageview控件来显示图像并调整大小,但文本会显示在图像的右侧。您可以使用以下代码,希望这个问题可以解决。

<?xml version="1.0" encoding="utf-8"?>

<ImageView
    android:id="@+id/icon"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:src="@drawable/ic_person" />

<TextView
    android:id="@+id/heading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:drawablePadding="5dp"
    android:gravity="top"
    android:padding="5dp"
    android:singleLine="true"
    android:text="heading"
    android:textSize="20dp"
    app:layout_constraintLeft_toRightOf="@+id/icon" />


0

编程解决方案:

您可以使用 drawable.setBounds,但它需要像素作为参数,而不是 dp。

如何转换:将像素转换为 dp

代码:

        Drawable drawable = getDrawable(R.drawable.ic_your_drawable);
        int size = dp2px(this, dpSize);
        if (drawable != null) {
            drawable.setBounds(0, 0, size, size);
        }

        textView.setCompoundDrawables(drawable, drawable, drawable, drawable); // should be (drawable, null, null, null) for you 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接