[英]Why view.height is 3 times bigger than actual height?
我有一個高度設置為 120dp 的 ImageView。 當我得到 view.height 時,它等於 360,為什么它不等於 120?
我不確定代碼不會有幫助,但是:
<ImageView
android:id="@+id/profilePic1"
android:layout_width="120dp"
android:layout_height="120dp"
android:scaleType="centerCrop"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:clickable="true"
app:srcCompat="@drawable/profile_pic1"/>
活動:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val layoutInflater: LayoutInflater = LayoutInflater.from(this)
val view: View = layoutInflater.inflate(R.layout.activity_edit_profile, null)
view.viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
// remove listener
view.viewTreeObserver.removeOnGlobalLayoutListener(this)
// insert coordinates (coor) of each image to imagePosition variables
Log.d("TAG", profilePic1.height.toString()) // RETURNS 360
}
})
因為在 xml 文件中,您在 DP 中給出了大小,而在 java 中,該參數以 Pixel 返回值,請檢查此以了解有關 DP 和 PIxel 的更多信息
https://developer.android.com/training/multiscreen/screendensities
36x36 (0.75x) for low-density (ldpi)
48x48 (1.0x baseline) for medium-density (mdpi)
72x72 (1.5x) for high-density (hdpi)
96x96 (2.0x) for extra-high-density (xhdpi)
144x144 (3.0x) for extra-extra-high-density (xxhdpi)
192x192 (4.0x) for extra-extra-extra-high-density (xxxhdpi)
這只是因為您使用的是XXHDPI
設備,其中 120dp 正在轉換為 360PX。
您應該閱讀mdpi、hdpi、xhdpi 和 xxhdpi 的圖像分辨率以了解 DP 和像素如何協同工作。 官方文檔可以在這里找到
如果我簡單地解釋一下,在MDPI
1dp 幾乎等於 1PX。 因此,如果您在MDPI
分辨率的設備上檢查代碼,您將獲得120PX
輸出。 但是當我在上面為其他分辨率添加了一個 URL 時,它遵循從 dp 到 PX 的轉換規則。 它會給你180px in HDPI, 240px in XHDPI, 360px in XXHDPI, 480px in XXXHDPI
設備作為輸出。
在 java 中,您以px
而不是dp
獲得高度。 您必須將其轉換為dp
才能獲得正確的數據:
float px = profilePic1.height;
float dp = px / context.getResources().getDisplayMetrics().density;
// here dp should be 120
因為您在檢索它時在代碼中以 dp(密度像素)為單位給出了高度,所以它僅以像素為單位進行檢索。 您必須將其轉換為 dp。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.