[英]Px to Dp conversion in Android
我遇到了需要以編程方式將TextView的寬度設置為50的情況。 我需要將此50轉換為dp,因為我沒有找到任何以編程方式將寬度設置為dp的規定。 任何人都可以幫助我如何在Android中將像素轉換為dps。
提前致謝。
這是我很久以前寫過的一些實用方法,它們似乎經常派上用場:
/**
* Converts pixel to dip.
*
* @param pixel
* that should be converted.
* @return the converted rounded dip.
*/
private int pixelToDip(int pixel) {
DisplayMetrics displayMetrics = mContext.getResources()
.getDisplayMetrics();
return (int) ((pixel / displayMetrics.density) + 0.5);
}
/**
* Converts dip to pixel.
*
* @param dip
* that should be converted.
* @return the converted rounded pixel.
*/
private int dipToPixel(int dip) {
DisplayMetrics displayMetrics = mContext.getResources()
.getDisplayMetrics();
return (int) ((dip * displayMetrics.density) + 0.5);
}
您要么必須在Context的子類中運行它,要么從某個地方獲取Context。 我在我的Utility類構造函數中傳入一個Context並將其存儲在mContext
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.