Open bingoogolapple opened 7 years ago
获取文字宽度
int textWidth = mPaint.measureText(text)
获取文字高度
int textHeight = mPaint.descent() - mPaint.ascent()
获取文字宽高
Rect textRect = new Rect(); mPaint.getTextBounds(text, 0, text.length(), textRect); int textWidth = textRect.width(); int textHeight = textRect.height();
private void test(Canvas canvas) { mPaint.setTextSize(BGAProgressBar.sp2px(getContext(), 24)); mPaint.setStyle(Paint.Style.FILL); mPaint.setStrokeWidth(BGAProgressBar.dp2px(getContext(), 1)); String text = "Android王浩Javajg"; float baseX = 30; float baseY = getMeasuredHeight() / 2; //获取FontMetrics对象,可以获得top,bottom,ascent,descent Paint.FontMetrics metrics = mPaint.getFontMetrics(); float top = baseY + metrics.top; float ascent = baseY + metrics.ascent; float descent = baseY + metrics.descent; float bottom = baseY + metrics.bottom; //绘制top mPaint.setColor(Color.CYAN); canvas.drawLine(0, top, getWidth(), top, mPaint); //绘制ascent mPaint.setColor(Color.GREEN); canvas.drawLine(0, ascent, getWidth(), ascent, mPaint); //绘制base mPaint.setColor(Color.MAGENTA); canvas.drawLine(0, baseY, getWidth(), baseY, mPaint); //绘制descent mPaint.setColor(Color.RED); canvas.drawLine(0, descent, getWidth(), descent, mPaint); //绘制bottom mPaint.setColor(Color.BLUE); canvas.drawLine(0, bottom, getWidth(), bottom, mPaint); //绘制文字 mPaint.setColor(Color.BLACK); canvas.drawText(text, baseX, baseY, mPaint); }