我想将我的文本(tp-TextPaint)置于我在画布上绘制的矩形语音气泡图中。有谁有想法吗?我已经使用canvas.drawText()实现了它,但我希望使用staticLayout来实现它,以便在调整画布宽度和高度时调整文本大小。以下是我的代码。
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
drawPath.reset();
drawPath.moveTo(0, 0);
drawPath.lineTo(getWidth(), 0);
drawPath.lineTo(getWidth(), 100);
drawPath.lineTo((getWidth()/2) +20, 100);
drawPath.lineTo(getWidth()/2, 140);
drawPath.lineTo((getWidth()/2)-20, 100);
drawPath.lineTo(0, 100);
drawPath.lineTo(0, 0);
canvas.drawPath(drawPath, drawPaint);
TextPaint tp = new TextPaint();
tp.setColor(Color.BLACK);
tp.setTextSize(25);
tp.setAntiAlias(true);
StaticLayout sl = new StaticLayout("" + s, tp, getWidth(),Alignment.ALIGN_CENTER, 1.0f, 0.0f, true);
sl.draw(canvas);
}
答案 0 :(得分:12)
这可能对你有帮助......
public static void drawText(Canvas canvas, Paint paint, String text) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int x = (canvas.getWidth() / 2) - (bounds.width() / 2);
int y = (canvas.getHeight() / 2) - (bounds.height() / 2);
canvas.drawText(text, x, y, paint);
}
答案 1 :(得分:2)
试一试:
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText("Hello", xPos, yPos, textPaint);