draw Multiline String - Java 2D Graphics

Java examples for 2D Graphics:Line

Description

draw Multiline String

Demo Code

/*/*from w  w w.  j ava2  s . co m*/
 * Copyright (C) 2013 Maciej G?rski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.util.Vector;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class Main{
    public static void drawMultilineString(Graphics g, String str, int x,
            int y, int anchor, int height) {
        String[] lines = StringUtils.split(str, '\n');
        drawStringArray(g, lines, x, y, anchor, height);
    }
    public static void drawStringArray(Graphics g, String[] array, int x,
            int y, int anchor, int height) {
        if (array == null) {
            return;
        }
        int fontHeight = g.getFont().getHeight();
        for (int i = 0; i < array.length; i++) {
            if (g.getTranslateY() + y + fontHeight <= 0) {
                y += fontHeight;
                continue;
            } else if (g.getTranslateY() + y - fontHeight >= height) {
                break;
            }
            drawString(g, array[i], x, y, anchor);
            y += fontHeight;
        }
    }
    public static void drawString(Graphics g, String str, int x, int y,
            int anchor) {
        if (!StringUtils.isNullOrEmpty(str)) {
            g.drawString(str, x, y, anchor);
        }
    }
    public static void drawString(Graphics g, String str, int x, int y,
            int anchor, int width) {
        int clipX = g.getClipX();
        int clipY = g.getClipY();
        int clipW = g.getClipWidth();
        int clipH = g.getClipHeight();
        g.setClip(x, y, width, g.getFont().getHeight());
        GraphicsUtils.drawString(g, str, x, y, anchor);
        g.setClip(clipX, clipY, clipW, clipH);
    }
}

Related Tutorials