Skip to content

Instantly share code, notes, and snippets.

@zzn2
Created March 10, 2015 07:20
Show Gist options
  • Save zzn2/71d679c7e0185dbea445 to your computer and use it in GitHub Desktop.
Save zzn2/71d679c7e0185dbea445 to your computer and use it in GitHub Desktop.
code snippet for drawing font metric lines
Typeface SANS_SERIF = createFromAsset(getContext(), "NotoSansCJKsc-Regular.otf", Typeface.SANS_SERIF);
@Override
protected void onDraw(Canvas canvas) {
drawText(canvas, 300, Typeface.DEFAULT, Color.RED, "Android Default");
drawText(canvas, 900, SANS_SERIF, Color.BLUE, "Source Han Sans SC Regular");
}
private void drawText(Canvas canvas, float y, Typeface typeface, int color, String name) {
String str = "你好 aloha";
float textSize = 120;
TextPaint paint = new TextPaint();
paint.setDither(true);
paint.setAntiAlias(true);
paint.setTypeface(typeface);
paint.setColor(color);
paint.setTextSize(40);
canvas.drawText(name, 0, y - 260, paint);
paint.setTextSize(textSize);
canvas.drawText(str, 100, y, paint);
Paint.FontMetrics metrics = paint.getFontMetrics();
drawLine(canvas, y, "baseline", color);
drawLine(canvas, y + metrics.ascent, "ascent", color);
drawLine(canvas, y + metrics.top , "top", color);
drawLine(canvas, y + metrics.bottom, "bottom", color);
drawLine(canvas, y + metrics.descent, "descent", color);
paint.setTextSize(30);
canvas.drawText(String.format("textSize=%.2f", textSize),
0, y + metrics.bottom + 100, paint);
canvas.drawText(String.format("ascent=%.2f, descent=%.2f", metrics.ascent, metrics.descent),
0, y + metrics.bottom + 140, paint);
canvas.drawText(String.format("top=%.2f, bottom=%.2f", metrics.top, metrics.bottom),
0, y + metrics.bottom + 180, paint);
canvas.drawText(String.format("leading=%.2f", metrics.leading),
0, y + metrics.bottom + 220, paint);
}
private void drawLine(Canvas canvas, float y, String name, int color) {
Paint paint = new Paint();
paint.setColor(color);
canvas.drawLine(0, y, 1000, y, paint);
canvas.drawText(name, 0, y, paint);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment