需求
在自定义View里面添加一种颜色表示某个数据到达了某个状态
问题
颜色没有显示
问题分析
在代码中定义一种颜色和画笔
private int wathetBlue;
private Paint backgroundWathetBlue;
在init方法里面初始化
wathetBlue = Color.argb(205, 165, 209, 254);
backgroundWathetBlue = new Paint();
backgroundWathetBlue.setColor(wathetBlue);
backgroundWathetBlue.setStyle(Paint.Style.FILL);
backgroundWathetBlue.setAntiAlias(true);
然后提供一个方法让外界调用
public void drawBlueHeight(float shejiDepth) {
sJDepth = shejiDepth;
depSJ = shejiDepth / maxHeight > 1 ? 1 : shejiDepth / maxHeight;
drawNowBlue = true;
invalidate();
}
此时调用了【invalidate();】方法之后,系统会调用
@Override
protected void onDraw(Canvas canvas) {
}
这一切都没有什么问题,但是最后却是没有显示,最后发现是因为
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
realWidth = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
if (realWidth == 0) {
realWidth = ScreenUtil.dip2px(getContext(), getContext().getResources().getDimension(com.southgnss.publiclibrary.R.dimen.dp_90));
height = ScreenUtil.dip2px(getContext(), getContext().getResources().getDimension(com.southgnss.publiclibrary.R.dimen.dp_314));
}
width = realWidth * 3 / 4;
setMeasuredDimension(realWidth, height);
}
在测量的时候,这个【height 】值刚开始是0,但是我将这个值为0的时候给传值给了我需要绘制的高度计算方法里面了,导致计算的结果不准确,然在【onDraw】里面调用这个错误的数据导致绘制失败。
提醒
在【onDraw】绘制的时候,此时自定义View的长和宽都是已经获取到实际的值,所以此时的View的大小是确定的,如果有需要的话,可以在这个时候获取自定义View的长和宽,然后再进行计算。提前在【onMeasure】里面获取值进行计算的话有可能会遇到值为自定义View的长和宽为0的情况。