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

How to design drawable left icon as circular (added using setCompoundDrawablesWithIntrinsicBounds) in Textview using java code (not xml)

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

如何在 java 中进行设计?

我在左边设置的代码

textview.setCompoundDrawablesWithIntrinsicBounds(
                    image, 0, 0, 0);

如何为上面的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"/>

加载您的图片

您需要将图像加载为位图。如果您从 drawable 获取 if ,您可以看到 How to convert a Drawable to a Bitmap?.

调整大小

您可以根据需要调整位图的大小以适合您的文本视图。参见 How to Resize a Bitmap in Android?

使角变圆

根据this post可以找到圆角的代码

代码示例

// 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);

输出

备注

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