[JAVA] text as bitmap And New Line

There is a guy who makes the text Bitmap, but what about line breaks? At times. Then do something with feeling!

TextToBitmap.java



    public static Bitmap textAsBitmap(String text , float textSize , int textColor){
        Typeface font = getTypeface(); // Get Your Typeface
        Paint paint = new Paint();
        paint.setTextSize(textSize);
        paint.setTypeface(font);
        paint.setColor(textColor);
        paint.setTextAlign(Paint.Align.LEFT);
        float baseline = -paint.ascent();
        int width,height;
        String message = "";
        String[] splitList = text.split("\n"); // new Line!!
        if(splitList.length != 0){
            for (String s : splitList) {
                if (message.length() < s.length()) {
                    message = s;
                }
            }
            width = (int)(paint.measureText(message)+0.5f); // round
            height = (int)((baseline * splitList.length)+paint.descent()+0.5f);
        } else {
            width = (int)(paint.measureText(text)+0.5f); // round
            height = (int)(baseline+paint.descent()+0.5f);
        }
        Bitmap image = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(image);
        if(splitList.length != 0){
            for(int i = 0 ; i < splitList.length ; i++ ){
                canvas.drawText(splitList[i], 0, baseline * (i+1), paint);
            }
        } else {
            canvas.drawText(text, 0, baseline, paint);
        }
        return image;
    }

Former story https://stackoverflow.com/questions/8799290/convert-string-text-to-bitmap

Recommended Posts

text as bitmap And New Line
String concatenation and line breaks
Old and new speed showdown