简体   繁体   中英

How to fit a background image to the screen of an Android device

I am using Eclipse to write an Android app. I want my app to display a background image which is stretched to the size of the screen.

I have written the following code, but in the emulator it immediately exited the app when I ran it. Could someone please help me to understand the problem...

Here is my code...

public class Roller extends Activity {

    Display display = getWindowManager().getDefaultDisplay(); 
    int dwidth = display.getWidth();
    int dheight = display.getHeight();
    Bitmap background1 = BitmapFactory.decodeResource(getResources(),R.drawable.sunnybackground);
    Bitmap BSunny = Bitmap.createScaledBitmap(background1,dwidth,dheight,true);

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new Panel(this));
    }

    class Panel extends View {
        public Panel(Context context) {
            super(context);
        }

        public void onDraw(Canvas canvas) {
            canvas.drawBitmap(BSunny, 0, 0, null);
        }
    }
}

Why don't you set the background image in the layout xml file? Do you have to set it programmatically at runtime?

I think you do as below (It seems that you can't get display info unless activity is created)

public class Roller extends Activity {

Bitmap BSunny;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    Display display = getWindowManager().getDefaultDisplay(); 
    int dwidth = display.getWidth();
    int dheight = display.getHeight();
    Bitmap background1 = BitmapFactory.decodeResource(getResources(),R.drawable.sunnybackground);
    BSunny = Bitmap.createScaledBitmap(background1,dwidth,dheight,true);

    setContentView(new Panel(this));
}

class Panel extends View {
    public Panel(Context context) {
        super(context);
    }

    public void onDraw(Canvas canvas) {
        canvas.drawBitmap(BSunny, 0, 0, null);
    }
}

}

Why not just something like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    ImageView iv = new ImageView(this, null);
    iv.setBackgroundResource(R.drawable.sunnybackground);
    setContentView(iv);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM