我已经以编程方式创建了一个ShapeDrawable,并希望在ImageView中显示它。如果我使用ImageView.setImageDrawable(),我将无法看到ShapeDrawable。如果我使用ImageView.setBackground(),它就能工作。
为什么ImageView.setImageDrawable()不能工作?
来自布局文件的ImageView:
<ImageView
android:id="@+id/myImageView"
android:layout_width="100dp"
android:layout_height="200dp" />活动的onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int x = 0;
int y = 0;
int width = 300;
int height = 250;
ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
drawable.getPaint().setColor(0xff74AC23);
drawable.setBounds(x, y, x + width, y + height);
ImageView iv = findViewById(R.id.myImageView);
iv.setBackground(drawable); // works
//iv.setImageDrawable(drawable); // doesn't work
}发布于 2018-05-23 09:55:43
要在ShapeDrawable中显示ImageView,您的ShapeDrawable应该具有定义的高度和宽度。将以下属性添加到ShapeDrawable中。
drawable.setIntrinsicHeight(height); drawable.setIntrinsicWidth(width);
发布于 2018-05-28 08:57:00
您还可以使用简单视图,只需使用setBackgroundDrawable将其背景绘图设置为形状即可。
ImageView可能无法显示您的形状,因为它没有默认大小。您可以使用sD.setIntrinsicWidth和sD.setIntrinsicHeight为您的形状提供默认的测试工具。
https://stackoverflow.com/questions/50398553
复制相似问题