harukazepc’s blog

インターネッツとAndroidなどが大好きです。あとは日々のことなど。

アプリの背景画像を、オリジナルサイズのまま中央寄せしたい(拡大・縮小無し)

アプリの背景画像を用意して、それを画面サイズに合わせるのではなく、

  • オリジナルサイズのまま(拡大・縮小なし)
  • 中央寄せ
  • はみ出る部分は無視

した状態でおきたい。

普通にlayout.xml等でlayoutに背景画像指定すると、画面サイズに縮小/拡大されてしまう。

Drawable Resources | Android Developersによると、

XML Bitmap

An XML bitmap is a resource defined in XML that points to a bitmap file. The effect is an alias for a raw bitmap file. The XML can specify additional properties for the bitmap such as dithering and tiling.

で出来るっぽいのだが、

background.xml
 <?xml version="1.0" encoding="utf-8"?>
 <bitmap
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:src="@drawable/background_src"
  android:gravity="top" />

で、@drawable/background を背景画像に指定しても、

XmlPullParserException: Binary XML file line #4: <bitmap> requires a valid src attribute

てなエラーに。ちゃんと@drawable/background_srcあるのに。。。

にっちもさっちもいかず、無理矢理やったのは、該当のActivity上で指定する方法。

        LinearLayout ll = (LinearLayout) findViewById(R.id.main_layout);
        BitmapDrawable bd = new BitmapDrawable(
        		getResources(),
        		BitmapFactory.decodeResource(
                		getResources(),R.drawable.background_src));
        bd.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);
        ll.setBackgroundDrawable(bd);

うーんこれでよいのだろうか(悪くはないだろうが

© harukazepc️