alexfu
2/4/2014 - 3:41 AM

Prevent your BitmapDrawables from scaling when using setBackground/setBackgroundDrawable. This is usually desired when you want to set an im

Prevent your BitmapDrawables from scaling when using setBackground/setBackgroundDrawable. This is usually desired when you want to set an image as your background.

public class DontScaleMe extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.alayout);
    ViewGroup parent = findViewById(R.id.root);
    
    Bitmap bitmap = obtainBitmapFromSomewhere();
    
    // This will scale your Bitmap to fit it's bounds.
    parent.setBackground(new BitmapDrawable(getResources(), bitmap));
    
    // This will not scale your Bitmap to fit it's bounds.
    // You can set any other kind of Gravity, doesn't have to be center.
    BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
    drawable.setGravity(Gravity.CENTER);
    parent.setBackground(drawable);
  }
}