android - 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
}
解决方案
要在 ImageView 中显示 ShapeDrawable,您的 ShapeDrawable 应定义高度和宽度。将以下属性添加到您的 ShapeDrawable。
drawable.setIntrinsicHeight(height);
drawable.setIntrinsicWidth(width);
推荐阅读
- javafx - Javafx 处理相同的窗口问题
- javascript - 在“代理”后面发送请求时代码不起作用
- dart - 如何在 Dart 中扩展现有的包/库?
- angular - Error displaying image using Capacitor and Ionic
- android - 为什么我的recyclerView在适配器通知数据更改后不显示新数据?
- angular - 基于服务结果的动态路径
- reactjs - Invariant Violation:对象作为 React 子对象无效(发现:带有键 {text,onPress} 的对象)
- java - 使用生成器函数创建有限流
- python - Python:在 Mac 上查找文件时出错
- html - next.js 中的 div 高度不是 100%