以编程方式创建的可绘制对象未显示在图像视图中

Programatically created drawable not shown in imageview

我正在尝试在图像视图中创建一个可绘制的矩形。

val backgroundRect = GradientDrawable()
backgroundRect.shape = GradientDrawable.RECTANGLE
backgroundRect.setBounds(0,0, 100, 100)
backgroundRect.setStroke(5, Color.parseColor("#585858"))
backgroundRect.setColor(Color.parseColor("#FF9009"))

val image = ImageView(context)
image.layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT)
image.setImageDrawable(backgroundRect)
rootView.addView(image)

问题是,如果我将 ImageView 布局参数设置为 WRAP_CONTENT,则不会显示任何内容,但如果我将参数设置为 image.layoutParams = ConstraintLayout.LayoutParams(100, 100) 然后显示 ImageView。我尝试使用 xml 创建矩形可绘制对象,如果我将其设置在那里,图像仍会显示。

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dummyRectangle"/>

我是否需要始终指定布局参数变量或是否有其他设置方法?

您应该为 backgroundRect 设置大小。 backgroundRect 没有任何大小,当您将其设置为包装内容时,它不会显示。

只需为您的GradientDrawable

设置一个尺寸
backgroundRect.setSize(100,100);

因为您的视图还没有大小。当您使用 wrap_content 时,您没有任何要包装的内容。

需要为至少一个图像视图指定大小或可绘制。

对于渐变可绘制对象,可以按照上面的回答完成,现在图像视图会根据可绘制对象的大小进行换行。

否则,如果根据文档给 imageview 指定了大小:-

The shape scales to the size of the container View proportionate to the dimensions defined here, by default. When you use the shape in an ImageView, you can restrict scaling by setting the android:scaleType to "center"

实现类似的替代方法(取决于用途):

1.Drawing 来自 xml 的可绘制对象。 // 在 xml 本身中定义 drawable 的大小。

2.You can also draw your shape as its own custom view and add it to a layout in your app.

3.create some custom drawings, you can do so by extending the Drawable class, later set in to imageview