Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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);
like image 981
patyoda Avatar asked Oct 19 '14 17:10

patyoda


1 Answers

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);
like image 64
Eugen Pechanec Avatar answered Sep 26 '22 06:09

Eugen Pechanec