Android自定义View基于Canvas绘制时如何在onDraw中正确设置宽高
自定义View 宽高配置不生效问题排查
现有实现的核心问题
- 你当前的
onMeasure逻辑完全是无效透传:调用super.onMeasure()后,再手动把系统算出的测量值重新设置一遍,没有任何自定义尺寸适配逻辑。 - 没有对传入的
widthMeasureSpec、heightMeasureSpec做模式解析,无法识别XML中声明的固定尺寸、match_parent、wrap_content三类布局规则,最终所有尺寸都被系统View的兜底默认值覆盖。 - 系统默认的View兜底逻辑对
wrap_content场景的处理是:把控件尺寸撑到和父容器等大,这也是你看到onDraw中拿到的宽高始终不符合预期的核心原因。
正确实现逻辑
需要根据MeasureSpec的三种匹配模式做对应处理,替代原来的无效透传:
- 当测量模式为
EXACTLY:直接使用父布局给出的尺寸值,对应XML中设置固定dp值、或者match_parent的场景 - 当测量模式为
AT_MOST:取自定义View内容所需的尺寸,和父布局允许的最大可用尺寸做最小值运算,对应wrap_content场景 - 当测量模式为
UNSPECIFIED:使用你设定的控件默认兜底尺寸
修正后的代码示例
// 自定义默认兜底尺寸,单位px private static final int DEFAULT_SIZE = 200; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 解析测量规格中的模式与可用尺寸 int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); int finalWidth; int finalHeight; // 宽度测量逻辑 if (widthMode == MeasureSpec.EXACTLY) { finalWidth = widthSpecSize; } else { // 替换为你Canvas内容实际需要的宽度计算逻辑 int desiredContentWidth = getPaddingLeft() + getPaddingRight() + getContentWidth(); if (widthMode == MeasureSpec.AT_MOST) { finalWidth = Math.min(desiredContentWidth, widthSpecSize); } else { finalWidth = DEFAULT_SIZE; } } // 高度测量逻辑 if (heightMode == MeasureSpec.EXACTLY) { finalHeight = heightSpecSize; } else { // 替换为你Canvas内容实际需要的高度计算逻辑 int desiredContentHeight = getPaddingTop() + getPaddingBottom() + getContentHeight(); if (heightMode == MeasureSpec.AT_MOST) { finalHeight = Math.min(desiredContentHeight, heightSpecSize); } else { finalHeight = DEFAULT_SIZE; } } setMeasuredDimension(finalWidth, finalHeight); }
额外注意事项
- onDraw方法中获取的
getWidth()、getHeight()值,完全来自onMeasure阶段最终设置的尺寸,只要测量逻辑正确,就不会出现拿到系统默认错误值的问题 - 不要在onMeasure中直接返回和测量规格无关的固定值,避免出现控件超出父布局边界的渲染异常
- 需要把padding值纳入内容尺寸的计算逻辑,避免内容绘制被控件padding裁剪
内容的提问来源于stack exchange,提问作者NikW
相关产品推荐
相关产品推荐

