package tech.starwin.utils;

import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

/**
 * Created by SiKang on 2018/11/22.
 */
public class ScreenAutoSize {
    public static void resizeDensity(Context context, float dpi) {
        DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics();
        float density = displayMetrics.density;
        final float[] scalldensity = {displayMetrics.scaledDensity};
        context.getApplicationContext().registerComponentCallbacks(new ComponentCallbacks() {
            @Override
            public void onConfigurationChanged(Configuration newConfig) {
                if (newConfig != null && newConfig.fontScale > 0) {
                    scalldensity[0] = context.getApplicationContext().getResources().getDisplayMetrics().scaledDensity;
                }
            }

            @Override
            public void onLowMemory() {
            }
        });
        float targetDensity = displayMetrics.widthPixels / dpi;
        float targetScallDensity = targetDensity * (scalldensity[0] / density);
        int targetDensityDpi = (int) targetDensity * 160;
        displayMetrics.density = targetDensity;
        displayMetrics.scaledDensity = targetScallDensity;
        displayMetrics.densityDpi = targetDensityDpi;
        DisplayMetrics thisDisplayMetrics = context.getResources().getDisplayMetrics();
        thisDisplayMetrics.density = targetDensity;
        thisDisplayMetrics.scaledDensity = targetScallDensity;
        thisDisplayMetrics.densityDpi = targetDensityDpi;
    }
}
