Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the relationship between pixels and scaled pixels

I used the layout editor in eclipse to mock up my ui layout and then I created the code to populate it dynamically and things are showing up as different sizes. The XML I use to add the star images looks like this:

<ImageView
android:src="@drawable/star_gold"
android:layout_height="22sp"
android:layout_width="22sp"
android:adjustViewBounds="true"
android:layout_marginLeft="2sp"
android:layout_marginRight="2sp" />

and the Java code I use to do the same thing looks like this:

ViewGroup.MarginLayoutParams layout = new ViewGroup.MarginLayoutParams(22, 22);
layout.setMargins(2, 0, 2, 0);
ImageView star = new ImageView(mContext);
star.setImageResource(R.drawable.star_gold);
star.setLayoutParams(layout);
star.setAdjustViewBounds(true);
holder.Stars.addView(star);

When I run my app on the G1 everything lines up and looks fine, but when I run it on the Droid the stars that I add via Java are about half the size of the ones I add in my XML. What do I need to do to make sure everything scales appropriately?

Edit: These are great responses, but I need to know how to do it from code. When I set the size it's in raw pixels, is there any way to set the size in dip's?

like image 874
CaseyB Avatar asked Jan 04 '10 17:01

CaseyB


2 Answers

Here we go! I need to get the DisplayMetrics Density.

// Convert the dips to pixels
final float scale = getContext().getResources().getDisplayMetrics().density;
mGestureThreshold = (int) (GESTURE_THRESHOLD_DIP * scale + 0.5f);

Thank you all for pointing me in the right direction!

like image 92
CaseyB Avatar answered Nov 18 '22 11:11

CaseyB


Firstly, you should be using Density Independent Pixels - dip or dp - and not Scaled Pixels - sp.

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen. If your resources are sized in dip they will get automatically scaled on a screens with different densities; this is why the stars specified in your XML look OK. Scaled Pixels are similar but should be used for text resources only since they also reflect text scaling options.

Your problem is that your Java code is working in unscaled raw pixels which is why your stars look smaller. The Android documentation has instructions on how to convert from dips to pixels. In short, you need to look at the android.util.DisplayMetrics.density field.

like image 19
Dave Webb Avatar answered Nov 18 '22 11:11

Dave Webb