您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“android中px、sp與dp之間怎么進行轉(zhuǎn)換”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“android中px、sp與dp之間怎么進行轉(zhuǎn)換”吧!
由于Android手機廠商很多,導(dǎo)致了不同設(shè)備屏幕大小和分辨率都不一樣,然而我們開發(fā)者要保持在不同設(shè)備上顯示同樣的視覺效果,就需要做一些適配效果。
屏幕大小:通常指的是屏幕對角線的長度,使用“寸”為單位來衡量。
分辨率:指手機屏幕的像素點個數(shù),例如:720*1280,指的是寬有720個像素點,高有1280個像素點。
dpi:指的是每英寸像素,是由對角線上的像素點數(shù)除以屏幕大小所得。
ldpi文件夾下對應(yīng)的密度為120dpi,對應(yīng)的分辨率為240*320
mdpi文件夾下對應(yīng)的密度為160dpi,對應(yīng)的分辨率為320*480
hdpi文件夾下對應(yīng)的密度為240dpi,對應(yīng)的分辨率為480*800
xhdpi文件夾下對應(yīng)的密度為320dpi,對應(yīng)的分辨率為720*1280
xxhdpi文件夾下對應(yīng)的密度為480dpi,對應(yīng)的分辨率為1080*1920
由于各種屏幕密度的不同,導(dǎo)致了同一張圖片在不同的手機屏幕上顯示不同;在屏幕大小相同的情況下,高密度的屏幕包含了更多的像素點。android系統(tǒng)將密度為160dpi的屏幕作為標(biāo)準(zhǔn)對于mdpi文件夾,在此屏幕的手機上1dp=1px。從上面系統(tǒng)屏幕密度可以得出各個密度值之間的換算;在mdpi中1dp=1px,在hdpi中1dp=1.5px,在xhdpi中1dp=2px,在xxhpi中1dp=3px。換算比例如下:ldpi:mdpi:hdpi:xhdpi:xxhdpi=3:4:6:8:12。
/** * dp轉(zhuǎn)換成px */ private int dp2px(Context context,float dpValue){ float scale=context.getResources().getDisplayMetrics().density; return (int)(dpValue*scale+0.5f); } /** * px轉(zhuǎn)換成dp */ private int px2dp(Context context,float pxValue){ float scale=context.getResources().getDisplayMetrics().density; return (int)(pxValue/scale+0.5f); } /** * sp轉(zhuǎn)換成px */ private int sp2px(Context context,float spValue){ float fontScale=context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue*fontScale+0.5f); } /** * px轉(zhuǎn)換成sp */ private int px2sp(Context context,float pxValue){ float fontScale=context.getResources().getDisplayMetrics().scaledDensity; return (int) (pxValue/fontScale+0.5f); }
private int dp2px(Context context,int dpValue){ return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpValue,context.getResources().getDisplayMetrics()); } private int sp2px(Context context,int spValue){ return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,spValue,context.getResources().getDisplayMetrics()); }
下面我們進行一下實驗: textSize的單位分別設(shè)置為sp和dp,然后改變系統(tǒng)字體大小
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="200dp" android:layout_height="wrap_content" android:text="尚硅谷科技" android:background="#ff0000" android:textSize="20sp"/> <TextView android:id="@+id/textView2" android:layout_width="200px" android:layout_height="wrap_content" android:text="尚硅谷科技" android:background="#00ff00" android:textSize="20dp"/> </LinearLayout>
1、用sp做單位,設(shè)置有效果
2、dp做單位沒有效果
到此,相信大家對“android中px、sp與dp之間怎么進行轉(zhuǎn)換”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。