validate String Bounds - Java 2D Graphics

Java examples for 2D Graphics:Dimension

Description

validate String Bounds

Demo Code


//package com.java2s;

import java.awt.Font;

import java.awt.Graphics;
import java.awt.Graphics2D;

import java.awt.Point;
import java.awt.Rectangle;

import java.awt.geom.Rectangle2D;

public class Main {
    public static void validateStringBounds(String text, Point position,
            Rectangle bounds, int buffer, Graphics g) {
        Font font = g.getFont();/*from   ww w  . ja va 2 s.  com*/
        Rectangle2D stringBounds = font.getStringBounds(text,
                ((Graphics2D) g).getFontRenderContext());
        if (position == null) {
            bounds.x = 0;
            bounds.y = 0;
            bounds.width = (int) (stringBounds.getWidth() + 2 * buffer);
            bounds.height = (int) (stringBounds.getHeight() + 2 * buffer);
        } else {
            bounds.x = (int) (position.x - stringBounds.getWidth() / 2 - buffer);
            bounds.y = (int) (position.y - stringBounds.getHeight() / 2 - buffer);
            bounds.width = (int) (stringBounds.getWidth() + 2 * buffer);
            bounds.height = (int) (stringBounds.getHeight() + 2 * buffer);
        }
    }
}

Related Tutorials