5

So I'm trying to somehow create a Path object in code (no XML) and draw it into an ImageView. Problem is I can't figure out any way to programmatically create ANY shape and have it show up in my ImageView. I can easily assign the ImageView to an XML resource and that works fine 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 should work, it compiles and runs without errors, but nothing happens. I tried to create a simple RectShape and assign the ImageView to it with setImageDrawable. Am I totally barking up the wrong tree here? I am extremely new to Android coding fyi, so I very well may be way off here. I do notice that I'm never manually drawing the rectangle, do I have to do that somewhere? I sort of figured the ImageView would take care of it, but maybe not. Let me know if you need more information about 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);
patyoda
  • 53
  • 1
  • 5

2 Answers2

12

I took a glance at the Drawable source and it looks like the XML tag <shape> inflates to GradientDrawable not ShapeDrawable. Replace your code with this:

GradientDrawable gd = new GradientDrawable();
gd.setShape(GradientDrawable.RECTANGLE);
gd.setColor(Color.BLACK);
imageView.setImageDrawable(gd);
Eugen Pechanec
  • 37,669
  • 7
  • 103
  • 124
  • Ah yes, that does it! Unfortunately that means my true purpose may not be possible, which was to set a Path object to a PathShape, to a ShapeDrawable, to the source of the ImageView. I'm not sure if there's a way to get a Path object into a GradientDrawable. But at least now I know how to make some shapes show up, thanks! – patyoda Oct 20 '14 at 13:54
  • In that case try combining [this](http://stackoverflow.com/questions/11495953/how-are-you-supposed-to-use-a-shapedrawable-with-a-pathshape-to-draw-a-line-on-a) and [that](http://stackoverflow.com/questions/9133051/shapedrawablefrom-a-pathshape-not-drawing-on-correct-coordinates). – Eugen Pechanec Oct 20 '14 at 13:59
  • Gotcha, will try. I appreciate the assistance. – patyoda Oct 20 '14 at 16:40
0

You must set width and height ShapeDrawable. In your code sample size is 0, so you don't see rect

sdRect.setIntrinsicWidth(50)
sdRect.setIntrinsicHeight(50)