如何使用java代码(不是xml)在Textview中将可绘制的左图标设计为圆形(使用setCompoundDrawablesWithIntrinsicBounds添加)

sej*_*ejn 5 java android textview android-drawable

我有一个文本视图,带有在 TextView 中呈现的图标。它有一个图像。我已经设置在文本的左侧。但我需要将图标设置为圆形。

我如何在java中设计它?

在此处输入图片说明

我的代码设置在左侧。

textview.setCompoundDrawablesWithIntrinsicBounds(
                    image, 0, 0, 0);
Run Code Online (Sandbox Code Playgroud)

如何为上述 textview drawableleft 图像设计圆形图像。

 <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="fill_vertical"
        android:ellipsize="end"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="-10dp"
        android:gravity="center"
        android:layout_marginLeft="15dp"
        android:minHeight="24dp"
        android:paddingLeft="@dimen/spacing_d2"
        android:paddingRight="@dimen/spacing_d2"
        android:tag="@string/tag_font_h_regular"
        android:fontFamily="@font/cachetbook"
        android:textColor="@color/white_new"
        android:textSize="12dp"
        tools:text="Universal Orlando Resort"/>
Run Code Online (Sandbox Code Playgroud)

axe*_*083 3

加载您的图像

您需要将图像加载为位图。如果您从可绘制对象中获取,您可以看到如何将可绘制对象转换为位图?

调整大小

您可以根据需要调整位图大小以适合您的文本视图。请参阅如何在 Android 中调整位图大小?

把角弄圆

根据这篇文章,您可以找到使角变圆的代码

代码示例

// Load your drawable
Drawable drawable = ContextCompat.getDrawable(this,R.drawable.ic_launcher_background);
// Convert it to a bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(drawableToBitmap((drawable)),50,50,false);
// Make the corner rounded
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
final float roundPx = (float) bitmap.getWidth() * 90f;
roundedBitmapDrawable.setCornerRadius(roundPx);
// Apply it to the TextView
((TextView) findViewById(R.id.test)).setCompoundDrawablesWithIntrinsicBounds(
                roundedBitmapDrawable, null, null, null);
Run Code Online (Sandbox Code Playgroud)

输出

在此输入图像描述

笔记

我不知道你为什么决定选择以编程方式执行此操作,但我不会推荐它,它更难控制视图和事物的位置。