我想要的是将视图转换为需要根视图的高度和宽度的位图。
getMeasuredHeight
和getMeasuredWidth
返回0
,传递的视图有效,但不返回高度和宽度
如何仅使用“自定义视图对象”的Java实例来获得有效的高度和宽度而不会膨胀“自定义 View ”类。
我正在使用以下代码片段获取视图的高度和宽度:
/**
* Return the width of view.
*
* @param view The view.
* @return the width of view
*/
public static int getMeasuredWidth(final View view) {
return measureView(view)[0];
}
/**
* Return the height of view.
*
* @param view The view.
* @return the height of view
*/
public static int getMeasuredHeight(final View view) {
return measureView(view)[1];
}
/**
* Measure the view.
*
* @param view The view.
* @return arr[0]: view's width, arr[1]: view's height
*/
public static int[] measureView(final View view) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp == null) {
lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
}
int widthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width);
int lpHeight = lp.height;
int heightSpec;
if (lpHeight > 0) {
heightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY);
} else {
heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
view.measure(widthSpec, heightSpec);
return new int[]{view.getMeasuredWidth(), view.getMeasuredHeight()};
}
答案 0 :(得分:0)
在展开并绘制视图之前,不会填充尺寸属性。获取属性的唯一方法是硬编码值,如果尺寸不是View.LayoutParams
或WRAP_CONTENT
,则从MATCH_PARENT
获取尺寸,或在onCreate()之后获取这些属性。活动或片段的onViewCreated()。
如果要将视图转换为位图,则可以在屏幕上绘制该视图(用户看不见该视图),然后从那里继续。