![](/img/trans.png)
[英]How to get ImageView Height and Width every time, before it is drawn to the UI (in a Fragment)
[英]How to get width and height of resized custom view , before it is drawn
在我的自定義 View .xml 中,我將寬度和高度定義為w = 600dp , h = 700dp
。 現在我知道 getMeasuredHeight()/getMeasuredWidth() 在繪制視圖后給出寬度和高度的值,它們可能與我在 .xml 文件中給出的不同,是否有一種解決方法來獲取getMeasuredHeight()
和getMeasuredWidth()
值之前視圖實際上是在布局上繪制的,而不使用onMeasure()
?
以及如何計算不同屏幕中更改的dp
大小? 就像我在模擬器上運行時的600h*700w
轉換為300*300
。
您可以覆蓋onSizeChanged()
以在繪制時獲取視圖的高度和寬度。請參閱以下內容:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mWidth = w;
mHeight = h;
super.onSizeChanged(w, h, oldw, oldh);
Log.d(TAG, "onSizeChanged: " + " width: " + w + " height: " + h + " oldw " + oldw + " oldh " + oldh);
}
要將 dp 轉換為像素,您可以使用以下代碼:
sizeInPixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
sizeInDp, getResources().getDisplayMetrics());
我遇到了同樣的問題。
這是我的解決方案,我是如何遇到這個類似問題的。 在使用OnPreDrawListener()
繪制圖像之前,您可以在那里獲得寬度和高度
ImageView iv= binding.photoRoundProfile;
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
private int mFinalWidth = 0;
private int mFinalHeight = 0;
public boolean onPreDraw() {
if(mFinalHeight != 0 || mFinalWidth != 0)
return true;
mFinalHeight = iv.getHeight();
mFinalWidth = iv.getWidth();
Log.d("hilength","Height: " + mFinalHeight + " Width: " + mFinalWidth);
ImageUtil.setPic(binding.photoRoundProfile, mCurrentPhotoPath);
return true;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.