Android中px與dip,sp與dip等的轉換工具類

來源:互聯網
上載者:User

標籤:android   style   blog   http   ar   strong   sp   on   log   

功能

通常在代碼中設定組件或文字大小隻能用px,通過這個工具類我們可以把dip(dp)或sp為單位的值轉換為以px為單位的值而保證大小不變。方法中的參數請參考http://www.cnblogs.com/wader2011/archive/2011/11/28/2266669.html

代碼

/**
 * Android大小單位轉換工具類
 *
 * @author wader
 *
 */
public class DisplayUtil {
 /**
  * 將px值轉換為dip或dp值,保證尺寸大小不變
  *
  * @param pxValue
  * @param scale(DisplayMetrics類中屬性density)
  * @return
  */
 public static int px2dip(float pxValue, float scale) {
  return (int) (pxValue / scale + 0.5f);
 }

 /**
  * 將dip或dp值轉換為px值,保證尺寸大小不變
  *
  * @param dipValue
  * @param scale(DisplayMetrics類中屬性density)
  * @return
  */
 public static int dip2px(float dipValue, float scale) {
  return (int) (dipValue * scale + 0.5f);
 }

 /**
  * 將px值轉換為sp值,保證文字大小不變
  *
  * @param pxValue
  * @param fontScale(DisplayMetrics類中屬性scaledDensity)
  * @return
  */
 public static int px2sp(float pxValue, float fontScale) {
  return (int) (pxValue / fontScale + 0.5f);
 }

 /**
  * 將sp值轉換為px值,保證文字大小不變
  *
  * @param spValue
  * @param fontScale(DisplayMetrics類中屬性scaledDensity)
  * @return
  */
 public static int sp2px(float spValue, float fontScale) {
  return (int) (spValue * fontScale + 0.5f);
 }
}

轉:http://www.cnblogs.com/wader2011/archive/2011/11/28/2266684.html

(轉)Android中px與dip,sp與dip等的轉換工具類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.