user2731584
user2731584

Reputation: 986

How to draw on the background of an android app?

I want to make some drawing on the background of a normal android app.

I know a canvas can be used to draw but my question is this :

1 - Is it possible for me to create a canvas as a background for an app with text views and buttons displayed above it ?

2 - Can canvas be created as a layer beneath the button and textviews ?

Upvotes: 0

Views: 919

Answers (2)

Barend
Barend

Reputation: 17444

The easiest way to do 1 is to just subclass the root layout of your window. For example, if your layout is currently this:

<?xml version="1.0"?>
<RelativeLayout ... >
    <!-- lots of views -->
</RelativeLayout>

Then you can simply create a class that extends RelativeLayout and redefine your view like this:

<?xml version="1.0"?>
<com.myapp.mypackage.MyCustomLayout ... >
    <!-- lots of views -->
</com.myapp.mypackage.MyCustomLayout>

The custom view class itself is going to look like this:

package com.myapp.mypackage;

//imports go here

public class MyCustomLayout extends RelativeLayout {

    public MyCustomLayout(Context c) {
        super(c);
        this.setWillNotDraw(false); //important
    }

    // Override other two superclass constructors as well

    @Override
    public void onDraw(Canvas canvas) {
        // Drawing code goes here.
        super.onDraw(canvas);
    }
}

Implementing this should automatically answer your question #2.

Upvotes: 1

sfridman
sfridman

Reputation: 441

  1. Yup. Everything you can do to a view via XML can be done dynamically via Java. For instance, instead of setting the background via the android:background attribute and a drawable in XML, you can set it with a call to View#setBackground. To set a Canvas image as the background all you'd need would be to throw a Drawable version of the Bitmap backing the Canvas into that method (and probably to call do it again every time the Canvas was updated). This isn't tested code, but it looks like you can do it in the following way:

    // Bitmap on which the Canvas calls will draw
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
    Canvas canvas = new Canvas(bitmap);
    // ... Draw on your canvas
    // Grab the view on which to set the background
    View main = findViewById(R.layout.activity_main);
    // We need the Bitmap as a Drawable
    BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
    // Set the background
    main.setBackground(drawable);
    // Hopefully it works!
    
  2. I don't see why not, at very least it could be done with a custom view.

Upvotes: 0

Related Questions