看网上看了好多,但是都有些复杂,就根据别人都现成的简化改装了一个
简单思路
自定义个矩形区域用来计算所需大小然后根据位置来写入文字
效果图
先创建个Point 弄个矩形并设置在seekbar顶部
//设置画笔
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(mTextColor);
mPaint.setTextSize(mTextSize);
//设置SeekBar顶部数值文字预留空间,左右为数值背景图片的一半,顶部为数值背景图片高度加五的间隔
setPadding((int) Math.ceil(mBgWidth) / 2, (int) Math.ceil(mBgHeight) + 5, (int) Math.ceil(mBgWidth) / 2, 0);
计算SeekBar数值文字的显示位置
/** * 计算SeekBar数值文字的显示位置 */
private void getTextLocation() {
// Paint.FontMetrics fm = mPaint.getFontMetrics();
mText = ""+getProgress();
//测量文字宽度
mTextWidth = mPaint.measureText(mText);
//计算文字基线Y坐标
mTextBaseLineY = mBgHeight ;/// 2 - fm.descent + (fm.descent - fm.ascent) / 2
}
重点是绘制方法,计算text的位置,然后绘制。 bgx就是根据控件的宽和进度在获取的
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
getTextLocation();
Rect bgRect = getProgressDrawable().getBounds();
//计算数值背景X坐标
float bgX = bgRect.width() * getProgress() / getMax();
//计算数值文字X坐标
float textX = bgX + (mBgWidth - mTextWidth) / 2;
canvas.drawText(mText, textX, mTextBaseLineY, mPaint);
}
注:其中的width和height,自己设置根据需求自己设置就可以。