ebtokyo
ebtokyo

Reputation: 2379

android, override the screen density

This is may be a crazy question but :

I would like to have a LayoutInflater where I could override the density so on a xxhdpi device 1dp will be 1 pixel, not 3 pixels.

Basically I have a FrameLayout (view) of 360x720dp, when I use :

FrameLayout viewToSnapshot = LayoutInflater.From(...).inflate(...);
Bitmap bitmap = Bitmap.createBitmap(viewToSnapshot.getMeasuredWidth(), viewToSnapshot.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
viewToSnapshot.draw(c);

On xxhdpi it create a 1080x2160px bitmap which is way too big. I want to create a 360x720px bitmap instead. I can rescale it but it may fail on OutOfMemoryError before.

PS: The use case is not to display the view on the screen but to generate a bitmap of the view.

Thanks !

Upvotes: 1

Views: 1440

Answers (1)

ebtokyo
ebtokyo

Reputation: 2379

I got what I wanted with this code which update the display metrics :

// Update the density used for the bitmap
final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
final float densityBefore = metrics.density;
final float scaledDensityBefore = metrics.scaledDensity;
metrics.density = 1.0f;
metrics.scaledDensity = 1.0f;
try {
  FrameLayout viewToSnapshot = LayoutInflater.from(context).inflate(...);
  Bitmap bitmap = Bitmap.createBitmap(viewToSnapshot.getMeasuredWidth(), viewToSnapshot.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
  Canvas c = new Canvas(bitmap);
  viewToSnapshot.draw(c);
  ...
} finally {
  metrics.density = densityBefore;
  metrics.scaledDensity = scaledDensityBefore;
}

Upvotes: 3

Related Questions