Is it possible to programmatically create a drawing and assign it to an ImageView?

So I am trying to somehow create a Path object in code (no XML) and draw it in an ImageView. The problem is I cannot figure out how to programmatically create ANY form and show it in my ImageView. I can easily assign ImageView to XML resource and it works like this:

imageView.setImageResource(R.drawable.resourcename);

      

Here's the XML file:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <size
        android:height="50dp"
        android:width="50dp" />
    <solid
        android:color="#00f"
        />
</shape>

      

But if I do something like this code below which I thought it should work, it compiles and runs without error, but nothing happens. I tried to create a simple RectShape and assign the ImageView to it using setImageDrawable. Am I totally barking the wrong tree here? I am extremely new to android fyi coding, so I might very well be here. I notice that I never manually draw a rectangle, do I need to do something? I sort of figured out that ImageView would take care of this, but maybe not. Let me know if you need more information on my code.

RectShape rect = new RectShape();
rect.resize(50,50);
ShapeDrawable sdRect = new ShapeDrawable(rect);
sdRect.getPaint().setColor(Color.BLACK);
sdRect.getPaint().setStyle(Paint.Style.FILL);
imageView.setImageDrawable(sdRect);

      

+3


source to share


1 answer


I took a look at the source of Drawable and it looks like the XML tag is <shape>

bloated to GradientDrawable

not ShapeDrawable

. Replace the code with the following:



GradientDrawable gd = new GradientDrawable();
gd.setShape(GradientDrawable.RECTANGLE);
gd.setColor(Color.BLACK);
imageView.setImageDrawable(gd);

      

+8


source







All Articles