android - ImageView setImageDrawable 不适用于 ShapeDrawable

标签 android

我以编程方式创建了一个 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
}

最佳答案

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

drawable.setIntrinsicHeight(高度); drawable.setIntrinsicWidth(宽度);

关于android - ImageView setImageDrawable 不适用于 ShapeDrawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50398553/

相关文章:

android - 如何将 Azure 服务总线通知中心的 IP 告诉 Google?

java - android中同时调用多个rest服务链接

android - 如何在横向模式和纵向模式之间使用 2 个不同的背景

android - 第一次通话时获取当前的 Facebook ID

android - 使用底部表深层链接打开 Activity 或 fragment

android - 如何解决 Xamarin Android 中的 SIGSEGV 崩溃问题

android - react native Android : unable to generate signed APK : "no such scale"

android - 在 Android 模拟器上运行 Cordova 错误 : "android: Command failed with exit code 2"

Android:Sqlite 从大 Blob 中崩溃

java - 下载管理器 getFilesDir()