像素和dip之间的相互转换

android不同屏幕之间像素和dip的转换比例是不一样的:

    2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
    1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
    3 px = 2 dip if dpi == 240(hdpi), 840x480

方法:

          // dip转像素
	public int DipToPixels(Context context, int dip) {
		final float SCALE = context.getResources().getDisplayMetrics().density;

		float valueDips = dip;
		int valuePixels = (int) (valueDips * SCALE + 0.5f);

		return valuePixels;

	}

	// 像素转dip
	public float PixelsToDip(Context context, int Pixels) {
		final float SCALE = context.getResources().getDisplayMetrics().density;

		float dips = Pixels / SCALE;

		return dips;

	}


 

你可能感兴趣的:(Android)