user007
user007

Reputation: 1084

widget size in pixels

How to get widget size in pixels?

I am using Note 3 smartphone, I took screenshot and calculated manually, should be 1020px x 316px (+-5px), 4x1widget (resizable).

I tried the code bellow, but I get wrong results: minW_dp=324dp, maxW_dp=439dp, minH_dp=69dp, maxH_dp=88dp. minW=782px, maxW=1060px, minH=167px, maxH=213px.

How to get real size of widget in pixels?

public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions)
{
    int minW_dp = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
    int maxW_dp = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
    int minH_dp = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
    int maxH_dp = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
    int minW = dpToPx(minW_dp, context);
    int maxW = dpToPx(maxW_dp, context);
    int minH = dpToPx(minH_dp, context);
    int maxH = dpToPx(maxH_dp, context);
    bitmap = Bitmap.createBitmap(minW, maxH, Config.ARGB_8888);
}

public static int dpToPx(int dp, Context context)
{
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
    return px;
}

Upvotes: 0

Views: 1701

Answers (1)

reVerse
reVerse

Reputation: 35254

Your dpToPx calculation is wrong. You need to change it from:

int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));

to

int px = Math.round(dp * displayMetrics.density);

If you read the Docs it gets obvious why your calculation couldn't work. (Note: DisplayMetrics.xdpi seems to be messed up on some devices as well, see this post)
Following what displayMetrics.xdpi represents:

The exact physical pixels per inch of the screen in the X dimension.

But you don't wanna get the pixels per inch of your screen. You wanna get the scale-factor, that's where displayMetrics.density comes into play:

The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

Note: The Note 3 is a xxhdpi device and thus has a scale-factor of 3.0 (480dpi).

Edit

An other way to calculate the dp->px:

(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, maxH_dp, context.getResources().getDisplayMetrics());

Upvotes: 1

Related Questions