I've created a ShapeDrawable
programmatically and want to display it in an ImageView
. If I use ImageView.setImageDrawable()
, I'm unable to see the ShapeDrawable
. If I use ImageView.setBackground()
, it works.
Why does ImageView.setImageDrawable()
not work?
ImageView from the layout file:
<ImageView
android:id="@+id/myImageView"
android:layout_width="100dp"
android:layout_height="200dp" />
Activity's 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
}
To display a ShapeDrawable in an ImageView, your ShapeDrawable should have height and width defined. Add the below properties to your ShapeDrawable.
drawable.setIntrinsicHeight(height);
drawable.setIntrinsicWidth(width);
You can also use a simple View and just set its background drawable to the shape using setBackgroundDrawable.
The ImageView probably can't display your shape because it has no default size. You can give your shape a default sizer using sD.setIntrinsicWidth and sD.setIntrinsicHeight.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With