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

时间:2018-08-19 06:56:24

标签: android kotlin android-drawable

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

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"/>

我是否需要始终指定layout params变量,还是有另一种设置方法?

3 个答案:

答案 0 :(得分:0)

您应该为backgroundRect设置大小。 backgroundRect没有任何大小,并且您设置它来包装不显示的内容。

答案 1 :(得分:0)

只需为您的AttributeError: 'DataFrame' object has no attribute '_get_object_id'

设置大小
GradientDrawable

因为您的视图尚无尺寸。并且当您使用wrap_content时,您没有要包装的任何内容。

答案 2 :(得分:0)

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

对于渐变可绘制对象,可以按照上面的回答进行操作,现在imageview根据可绘制对象的大小进行包装。

否则,根据文档为imageview指定大小:-

  

默认情况下,形状会按此处定义的尺寸与容器视图的大小成比例。在ImageView中使用形状时,可以通过将android:scaleType设置为“ center”来限制缩放比例

实现相似性的替代方法(取决于使用情况):

1。从xml绘制可绘制对象。 //在xml本身中定义可绘制的大小。

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

相关问题