1.使用画笔绘制一张Bitmap
Canvas canvas = null;
Bitmap bitmap = null;
try {
TextPaint textPaint = new TextPaint();
textPaint.setColor(Color.argb(255, 0, 0, 255));
textPaint.setTypeface(Typeface.SANS_SERIF);
textPaint.setTextSize(60);
Paint bgPaint = new Paint();
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setARGB(127, 0, 0, 0);
int bmpWidth = (int) textPaint.measureText(content);
if (bmpWidth % 4 != 0) {
bmpWidth = bmpWidth - bmpWidth % 4 + 4;
}
Paint.FontMetrics fm = textPaint.getFontMetrics();
int bmpHeight = (int) Math.ceil(fm.bottom - fm.top);
if (bmpHeight % 4 != 0) {
bmpHeight = bmpHeight - bmpHeight % 4 + 4;
}
bitmap = Bitmap.createBitmap(bmpWidth, bmpHeight, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawRect(0, 0, bmpWidth, bmpHeight, bgPaint);
canvas.drawText(content, 0, Math.abs(fm.top), textPaint);
} catch (StringIndexOutOfBoundsException e) {
return false;
} catch (Exception e) {
return false;
}
FontMetrics源码
/**
* Class that describes the various metrics for a font at a given text size.
* Remember, Y values increase going down, so those values will be positive,
* and values that measure distances going up will be negative. This class
* is returned by getFontMetrics().
*/
public static class FontMetrics {
/**
* The maximum distance above the baseline for the tallest glyph in
* the font at a given text size.
*/
public float top;
/**
* The recommended distance above the baseline for singled spaced text.
*/
public float ascent;
/**
* The recommended distance below the baseline for singled spaced text.
*/
public float descent;
/**
* The maximum distance below the baseline for the lowest glyph in
* the font at a given text size.
*/
public float bottom;
/**
* The recommended additional space to add between lines of text.
*/
public float leading;
}
FontMetrics使用说明请参考:https://blog.csdn.net/u012551350/article/details/51361778
ascent = ascent线的y坐标 - baseline线的y坐标;//负数
descent = descent线的y坐标 - baseline线的y坐标;//正数
top = top线的y坐标 - baseline线的y坐标;//负数
bottom = bottom线的y坐标 - baseline线的y坐标;//正数
leading = top线的y坐标 - ascent线的y坐标;//负数