public class MyView extends View {
private Paint mPaint = new Paint();
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
mPaint.reset();
mPaint.setColor(Color.WHITE);
mPaint.setTextSize(80);
//设置字体为斜体
mPaint.setTypeface(Typeface.create("", Typeface.ITALIC));
// FontMetrics对象
FontMetrics fontMetrics = mPaint.getFontMetrics();
String text = "中国话fgiqÃÇŸŒú";
// 计算每一个坐标
float textWidth = mPaint.measureText(text);
float baseX = 30;
float baseY = 700;
float topY = baseY + fontMetrics.top;
float ascentY = baseY + fontMetrics.ascent;
float descentY = baseY + fontMetrics.descent;
float bottomY = baseY + fontMetrics.bottom;
// 绘制文本
canvas.drawText(text, baseX, baseY, mPaint);
// BaseLine描画
mPaint.setColor(Color.RED);
canvas.drawLine(baseX, baseY, baseX + textWidth, baseY, mPaint);
mPaint.setTextSize(20);
canvas.drawText("base", baseX + textWidth, baseY, mPaint);
// Base描画
canvas.drawCircle(baseX, baseY, 5, mPaint);
// TopLine描画
mPaint.setColor(Color.LTGRAY);
canvas.drawLine(baseX, topY, baseX + textWidth, topY, mPaint);
canvas.drawText("top", baseX + textWidth, topY, mPaint);
// AscentLine描画
mPaint.setColor(Color.GREEN);
canvas.drawLine(baseX, ascentY, baseX + textWidth, ascentY, mPaint);
canvas.drawText("ascent", baseX + textWidth, ascentY + 10, mPaint);
// DescentLine描画
mPaint.setColor(Color.YELLOW);
canvas.drawLine(baseX, descentY, baseX + textWidth, descentY, mPaint);
canvas.drawText("descent", baseX + textWidth, descentY, mPaint);
// ButtomLine描画
mPaint.setColor(Color.MAGENTA);
canvas.drawLine(baseX, bottomY, baseX + textWidth, bottomY, mPaint);
canvas.drawText("buttom", baseX + textWidth, bottomY + 10, mPaint);
super.onDraw(canvas);
}
}
FontMetrics.top的数值是个负数,其绝对值就是字体绘制边界到baseline的距离。
所以如果是把文字画在 FontMetrics高度的矩形中, drawText就应该传入 -FontMetrics.top。
要画在targetRect的居中位置,baseline的计算公式就是(本人抄的原博主的,也不知道怎么计算的):
targetRect.top + (targetRect.bottom - targetRect.top) / 2 - (FontMetrics.bottom - FontMetrics.top) / 2 - FontMetrics.top
参考:http://blog.csdn.net/hursing/article/details/18703599
参考:http://blog.jobbole.com/70468/