Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView setImageDrawable not working for ShapeDrawable

Tags:

android

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
}
like image 399
tronman Avatar asked May 17 '18 18:05

tronman


2 Answers

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);

like image 57
Atchyut Maddukuri Avatar answered Sep 28 '22 02:09

Atchyut Maddukuri


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.

like image 39
Mohsin mithawala Avatar answered Sep 28 '22 00:09

Mohsin mithawala