Last active
November 24, 2016 21:05
-
-
Save AndriyBas/26183b52fc93ad0d6fdbd344ff712cb4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@NonNull | |
private Bitmap createBitmap(@NonNull TextLayer textLayer, @Nullable Bitmap reuseBmp) { | |
int boundsWidth = canvasWidth; | |
// init params - size, color, typeface | |
textPaint.setStyle(Paint.Style.FILL); | |
textPaint.setTextSize(textLayer.getFont().getSize() * canvasWidth); | |
textPaint.setColor(textLayer.getFont().getColor()); | |
textPaint.setTypeface(fontProvider.getTypeface(textLayer.getFont().getFace())); | |
// drawing text guide : http://ivankocijan.xyz/android-drawing-multiline-text-on-canvas/ | |
// Static layout which will be drawn on canvas | |
StaticLayout sl = new StaticLayout( | |
textLayer.getText(), // - text which will be drawn | |
textPaint, | |
boundsWidth, // - width of the layout | |
Layout.Alignment.ALIGN_CENTER, // - layout alignment | |
1, // 1 - text spacing multiply | |
1, // 1 - text spacing add | |
true); // true - include padding | |
// calculate height for the entity, min - Limits.MIN_BITMAP_HEIGHT | |
int boundsHeight = sl.getHeight(); | |
// create bitmap not smaller than TextLayer.Limits.MIN_BITMAP_HEIGHT | |
int bmpHeight = (int) (canvasHeight * Math.max(TextLayer.Limits.MIN_BITMAP_HEIGHT, | |
1.0F * boundsHeight / canvasHeight)); | |
// create bitmap where text will be drawn | |
Bitmap bmp; | |
if (reuseBmp != null && reuseBmp.getWidth() == boundsWidth | |
&& reuseBmp.getHeight() == bmpHeight) { | |
// if previous bitmap exists, and it's width/height is the same - reuse it | |
bmp = reuseBmp; | |
bmp.eraseColor(Color.TRANSPARENT); // erase color when reusing | |
} else { | |
bmp = Bitmap.createBitmap(boundsWidth, bmpHeight, Bitmap.Config.ARGB_8888); | |
} | |
Canvas canvas = new Canvas(bmp); | |
canvas.save(); | |
// move text to center if bitmap is bigger that text | |
if (boundsHeight < bmpHeight) { | |
//calculate Y coordinate - In this case we want to draw the text in the | |
//center of the canvas so we move Y coordinate to center. | |
float textYCoordinate = (bmpHeight - boundsHeight) / 2; | |
canvas.translate(0, textYCoordinate); | |
} | |
//draws static layout on canvas | |
sl.draw(canvas); | |
canvas.restore(); | |
return bmp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment