带节点的进度条
代码地址:https://github.com/mygzk/NodeProgress.git
在构造函数中获取自定义属性
自定义view 重写onDraw()方法
关键代码:
-
在onMeasure()方法计算控件宽度 高度 初始化节点个数
-
在onDraw()中画内容分三步分
-
画线
-
画节点
-
画文字
核心代码:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
int d = (mWidth - getPaddingLeft() - getPaddingRight()) / (mNumber - 1);
nodes = new ArrayList<>();
for (int i = 0; i < mNumber; i++) {
if (i == 0) {
Node node = new Node();
Point paint = new Point(getPaddingLeft() + mNodeRadio, mHeight / 2);
node.setPoint(paint);
node.setDes("第" + (i + 1) + "个");
nodes.add(node);
continue;
}
if (i == mNumber - 1) {
Node node = new Node();
Point paint = new Point(mWidth - getPaddingRight() - mNodeRadio, mHeight / 2);
node.setPoint(paint);
node.setDes("第" + (i + 1) + "个");
nodes.add(node);
continue;
}
Node node = new Node();
Point paint = new Point(getPaddingLeft() + d * i - mNodeRadio, mHeight / 2);
node.setPoint(paint);
node.setDes("第" + (i + 1) + "个");
nodes.add(node);
}
}
private void drawLineProgress(Canvas canvas) {
int startX = getPaddingLeft() + mNodeRadio * 2;
for (int i = 1; i < nodes.size(); i++) {
Node node = nodes.get(i);
Point point = node.getPoint();
int x = point.x;
int y = point.y;
x = x - mNodeRadio;
if (mCurentNode >= i) {
canvas.drawLine(startX, y, x, y, mLineProgressPaint);
} else {
canvas.drawLine(startX, y, x, y, mLinePaint);
}
startX = x + mNodeRadio * 2;
}
}
private void drawNodeProgress(Canvas canvas) {
for (int i = 0; i < nodes.size(); i++) {
Node node = nodes.get(i);
Point point = node.getPoint();
if (mCurentNode >= i) {
if (mNodeProgressBitmap != null) {
Rect b1 = new Rect(0, 0, mNodeProgressBitmap.getWidth(), mNodeProgressBitmap.getHeight());
Rect b = new Rect(point.x - mNodeRadio, point.y - mNodeRadio,
point.x + mNodeRadio, point.y + mNodeRadio);
canvas.drawBitmap(mNodeProgressBitmap, b1, b, mNodePaint);
} else {
canvas.drawCircle(point.x, point.y, mNodeRadio, mNodeProgressPaint);
}
} else {
if (mNodeBitmap != null) {
Rect b1 = new Rect(0, 0, mNodeBitmap.getWidth(), mNodeBitmap.getHeight());
Rect b = new Rect(point.x - mNodeRadio, point.y - mNodeRadio,
point.x + mNodeRadio, point.y + mNodeRadio);
canvas.drawBitmap(mNodeBitmap, b1, b, mNodePaint);
} else {
canvas.drawCircle(point.x, point.y, mNodeRadio, mNodePaint);
}
}
}
}
private void drawTextProgress(Canvas canvas) {
for (int i = 0; i < nodes.size(); i++) {
Node node = nodes.get(i);
Point point = node.getPoint();
String text = node.getDes();
Paint.FontMetricsInt fmi = mTextPaint.getFontMetricsInt();
if (mCurentNode >= i) {
canvas.drawText(text, point.x, point.y + mNodeRadio + fmi.bottom - fmi.top, mTextProgressPaint);
} else {
canvas.drawText(text, point.x, point.y + mNodeRadio + fmi.bottom - fmi.top, mTextPaint);
}
}
}
上效果图:
0.png
网友评论