【发布时间】:2019-05-14 08:29:43
【问题描述】:
我想要的是将视图转换为我需要根视图的高度和宽度的位图。
getMeasuredHeight 和 getMeasuredWidth 正在返回 0,通过 View 有效但不返回高度和宽度,
我怎样才能在不膨胀自定义 View 类的情况下获得有效的高度和宽度,只使用自定义视图对象的 java 实例。
我正在使用以下片段来获取视图的高度和宽度:
/**
* 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()};
}
【问题讨论】:
标签: android android-layout android-custom-view android-bitmap