首页 > 解决方案 > ImageView setImageDrawable 不适用于 ShapeDrawable

问题描述

我以ShapeDrawable编程方式创建了一个并希望将其显示在ImageView. 如果我使用ImageView.setImageDrawable(),我无法看到ShapeDrawable。如果我使用ImageView.setBackground(),它可以工作。

为什么不ImageView.setImageDrawable()工作?

布局文件中的 ImageView:

<ImageView
    android:id="@+id/myImageView"
    android:layout_width="100dp"
    android:layout_height="200dp" />

Activity 的 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
}

标签: android

解决方案


要在 ImageView 中显示 ShapeDrawable,您的 ShapeDrawable 应定义高度和宽度。将以下属性添加到您的 ShapeDrawable。

drawable.setIntrinsicHeight(height); drawable.setIntrinsicWidth(width);


推荐阅读