我正在尝试绘制一个自定义视图,除了右侧部分被截断之外,一切都渲染正常。我想让视图填满父元素,并仅使用所需高度(即我正在绘制的位图的高度)。当我从活动的xml布局中删除填充时,自定义视图就可以正常渲染了。因此,我没有考虑父元素的填充来计算onMeasure。
请问是否有人可以查看一下这段代码并描述我错在哪里以及如何解决问题?谢谢。
编辑后包括@nicko的答案和更多详细信息:
请问是否有人可以查看一下这段代码并描述我错在哪里以及如何解决问题?谢谢。
编辑后包括@nicko的答案和更多详细信息:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
ViewParent parent = getParent();
int leftPadding = 0;
int rightPadding = 0;
if (parent instanceof ViewGroup) {
leftPadding = ((ViewGroup) parent).getPaddingLeft();
rightPadding = ((ViewGroup) parent).getPaddingRight();
}
float wanabeHeight = calendar.getHeight();
float wanabeWidth = parentWidth - leftPadding - rightPadding;
int height = 0;
//Determine Height
switch(heightMode){
case MeasureSpec.EXACTLY: height = parentHeight;
break;
case MeasureSpec.AT_MOST:
height = Math.min((int)wanabeHeight, parentHeight);
break;
case MeasureSpec.UNSPECIFIED:
default:
height = (int)wanabeHeight;
break;
}
setMeasuredDimension((int)wanabeWidth, height);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
calendarX = left;
personX = (int)((right - left) * 0.5);
checkX = right - check.getWidth() - getPaddingRight();
lineY = (int)((bottom - top) * 0.5);
bitmapY = (int)(((bottom - top) * 0.5) - (calendar.getHeight() * 0.5));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(calendar, calendarX, bitmapY, paint);
canvas.drawBitmap(person, personX, bitmapY, paint);
canvas.drawBitmap(check, checkX, bitmapY, paint);
canvas.drawLine((calendarX + calendar.getWidth() + PADDING), lineY, personX - PADDING, lineY, linePaint);
canvas.drawLine((personX + person.getWidth() + PADDING), lineY, checkX - PADDING, lineY, linePaint);
}