[英]How to get width and height of resized custom view , before it is drawn
In my custom View .xml , i have defined width and height as w = 600dp , h = 700dp
.在我的自定义 View .xml 中,我将宽度和高度定义为
w = 600dp , h = 700dp
。 Now i know getMeasuredHeight() / getMeasuredWidth() give values of width and height after view is drawn and they may differ from what i've given in .xml file , is there a workaround to get getMeasuredHeight()
and getMeasuredWidth()
values before view is actually drawn on layout, without use of onMeasure()
?现在我知道 getMeasuredHeight()/getMeasuredWidth() 在绘制视图后给出宽度和高度的值,它们可能与我在 .xml 文件中给出的不同,是否有一种解决方法来获取
getMeasuredHeight()
和getMeasuredWidth()
值之前视图实际上是在布局上绘制的,而不使用onMeasure()
?
And How to calculate changed dp
sizes in different screens ?以及如何计算不同屏幕中更改的
dp
大小? like my 600h*700w
when run on emulator converts to 300*300
.就像我在模拟器上运行时的
600h*700w
转换为300*300
。
You can override onSizeChanged()
to get height and width of the view when it is drawn.refer below:您可以覆盖
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);
}
To convert dp into pixels you can use following code:要将 dp 转换为像素,您可以使用以下代码:
sizeInPixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
sizeInDp, getResources().getDisplayMetrics());
I had kind of the same problem.我遇到了同样的问题。
Here is my solution, how I came across this similar problem.这是我的解决方案,我是如何遇到这个类似问题的。 There you can get the Width and Height before the Image is drawn with
OnPreDrawListener()
在使用
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.