繁体   English   中英

如何在绘制之前获取调整大小的自定义视图的宽度和高度

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM