Today i creaded a small method to draw some text to a fixed area in a canvas:
private static void drawText(Canvas canvas, int xStart, int yStart,
int xWidth, int yHeigth, String textToDisplay,
TextPaint paintToUse, float startTextSizeInPixels,
float stepSizeForTextSizeSteps) {
// Text view line spacing multiplier
float mSpacingMult = 1.0f;
// Text view additional line spacing
float mSpacingAdd = 0.0f;
StaticLayout l = null;
do {
paintToUse.setTextSize(startTextSizeInPixels);
startTextSizeInPixels -= stepSizeForTextSizeSteps;
l = new StaticLayout(textToDisplay, paintToUse, xWidth,
Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
} while (l.getHeight() > yHeigth);
int textCenterX = xStart + (xWidth / 2);
int textCenterY = (yHeigth - l.getHeight()) / 2;
canvas.save();
canvas.translate(textCenterX, textCenterY);
l.draw(canvas);
canvas.restore();
}
I recommend to use a TextPaint like this:
textPaint = new TextPaint();
textPaint.setColor(Color.RED);
textPaint.setShadowLayer(SHADOW_LAYER_SIZE, 1, 1, Color.BLACK);
textPaint.setTextAlign(Align.CENTER);
textPaint.setAntiAlias(true);
And the following method to calculate the pixel size for a given DIP size:
private int dipToPixels(int dipValue) {
Resources r = getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dipValue, r.getDisplayMetrics());
return px;
}
The the startTextSizeInPixels could be something like:
startTextSizeInPixels = dipToPixels(22);
private static void drawText(Canvas canvas, int xStart, int yStart,
int xWidth, int yHeigth, String textToDisplay,
TextPaint paintToUse, float startTextSizeInPixels,
float stepSizeForTextSizeSteps) {
// Text view line spacing multiplier
float mSpacingMult = 1.0f;
// Text view additional line spacing
float mSpacingAdd = 0.0f;
StaticLayout l = null;
do {
paintToUse.setTextSize(startTextSizeInPixels);
startTextSizeInPixels -= stepSizeForTextSizeSteps;
l = new StaticLayout(textToDisplay, paintToUse, xWidth,
Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
} while (l.getHeight() > yHeigth);
int textCenterX = xStart + (xWidth / 2);
int textCenterY = (yHeigth - l.getHeight()) / 2;
canvas.save();
canvas.translate(textCenterX, textCenterY);
l.draw(canvas);
canvas.restore();
}
I recommend to use a TextPaint like this:
textPaint = new TextPaint();
textPaint.setColor(Color.RED);
textPaint.setShadowLayer(SHADOW_LAYER_SIZE, 1, 1, Color.BLACK);
textPaint.setTextAlign(Align.CENTER);
textPaint.setAntiAlias(true);
And the following method to calculate the pixel size for a given DIP size:
private int dipToPixels(int dipValue) {
Resources r = getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dipValue, r.getDisplayMetrics());
return px;
}
The the startTextSizeInPixels could be something like:
startTextSizeInPixels = dipToPixels(22);