如何将背景图像适合Android设备的屏幕

时间:2010-12-28 23:35:47

标签: java android image background

我正在使用Eclipse编写Android应用程序。我希望我的应用程序显示一个拉伸到屏幕大小的背景图像。

我编写了以下代码,但在模拟器中,当我运行它时它会立即退出应用程序。请有人帮我理解这个问题......

这是我的代码......

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);
        }
    }
}

3 个答案:

答案 0 :(得分:0)

为什么不是这样的:

@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);
}

答案 1 :(得分:0)

为什么不在布局xml文件中设置背景图片? 您是否必须在运行时以编程方式设置它?

答案 2 :(得分:0)

我认为你这样做 (除非创建活动,否则您似乎无法获取显示信息)

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);
    }
}

}