0

I need to be able to create a custom image through code, and then set that image to an imageview

I want this image to have a solid background colour, a title and an icon. I want it to be customisable so that I can call to create an image with values for example

createImage(String bckgColourHex, String title, int iconResource){
 // create image using value here

return image.
}

Then I can use the drawable to set it to my imageView

This is what I am trying so far

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView image = (ImageView) findViewById(R.id.imageView1);

        BitmapDrawable customImage = writeOnDrawable(R.drawable.background_gradient, "TEXT GOES HERE");
        image.setBackgroundDrawable(customImage);

    }


    public BitmapDrawable writeOnDrawable(int drawableId, String text){

        Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
        Paint paint = new Paint(); 
        paint.setStyle(Style.FILL);  
        paint.setColor(Color.BLACK); 
        paint.setTextSize(20); 

        Canvas canvas = new Canvas(bm);
        canvas.drawText(text, 0, bm.getHeight()/2, paint);

        return new BitmapDrawable(bm);
    }

Thank you

1 Answer 1

1
 public static Drawable makeBorderedDrawable(Context mContext, int width, String xCode, Boolean unAvail) {

    Paint p = new Paint();
    Bitmap bkg = null;
    final int FULL_ALPHA = 0xFF123456; // of whatever color you want

    int pixel = FULL_ALPHA;

    // first create a mutable bitmap
    bkg = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);

    Canvas c = new Canvas(bkg);

    p.setColor(pixel);
    c.drawCircle(width / 2, width / 2, width / 2, p);

    // or draw rect, or lines, or drawtext....or whatever


    return new BitmapDrawable(mContext.getResources(), bkg);

    // or you could return a Bitmap if you prefer.

}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, could you please explain what the xcode and Boolean are for. thanks
Got it working, thank you for pointing my in the right direction :)
xCode was simple a hex value for RGB. The boolean I used to draw different aspects based on business logic. Sorry I wasn't more clear

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.