ser*_*kye 5 android android-view
我正在尝试绘制一个自定义视图,一切都很好,除了最右边的部分被切断.我希望视图填充父级,只使用所需的高度(即我正在绘制的位图的高度.当我从活动的xml布局中删除填充时,自定义视图渲染得很好.所以我不是计算onMeasure并考虑父母填充.
请有人看看这段代码,并描述我为什么以及如何出错?谢谢
编辑包括@ 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);
}
Run Code Online (Sandbox Code Playgroud)
在 中onDraw,所有内容都相对于画布 - 但似乎您是根据相对于onLayout屏幕的视图位置来绘制所有内容。
因此,对于右手图像,您实际上需要像这样计算 X 位置:
checkX = right - left - check.getWidth();
Run Code Online (Sandbox Code Playgroud)
您还可能会发现,如果父级有任何填充,左侧图像会缩进一点,因此请尝试将其定位在 0:
calendarX = 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2254 次 |
| 最近记录: |