All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eu.hansolo.steelseries.tools.Util Maven / Gradle / Ivy

Go to download

The SteelSeries is a javabeans component library that contains gauges. You will find linear and radial gauges. In addition you will also find digital displays.

There is a newer version: 3.9.6
Show newest version
package eu.hansolo.steelseries.tools;


/**
 * A set of handy methods that will be used all over
 * the place.
 * @author hansolo
 */
public enum Util
{
    INSTANCE;

    private final float INT_TO_FLOAT_CONST = 1f / 255f;
    private final java.util.regex.Pattern NUMBERS_ONLY = java.util.regex.Pattern.compile("^[-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?$");
    private final java.util.regex.Matcher MATCHES_NUMBERS = NUMBERS_ONLY.matcher("");
    private java.awt.Font digitalFont = null;
    private java.awt.Font standardFont = new java.awt.Font("Verdana", 1, 24);
    private final java.awt.geom.Rectangle2D TEXT_BOUNDARY = new java.awt.geom.Rectangle2D.Double(0, 0, 10, 10);

    /**
     * A class that contains some useful methods related to the PointOfInterest class and
     * to general ui related things.
     */
    Util()
    {
        try
        {
            digitalFont = java.awt.Font.createFont(0, this.getClass().getResourceAsStream("/eu/hansolo/steelseries/resources/lcd.ttf"));
            java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(digitalFont);
        }
        catch (java.awt.FontFormatException exception)
        {

        }
        catch (java.io.IOException exception)
        {
            
        }
    }

    // 
    //********************************** UI related utils **************************************************************
    /**
     * It will take the font from the given Graphics2D object and returns a shape of the given TEXT
     * that is rotated by the ROTATION_ANGLE around it's center which is defined
     * by TEXT_POSITION_X and TEXT_POSITION_Y. It will take the font's descent into account so that
     * the rotated text will be centered correctly even if it doesn't contain characters with descent.
     * @param G2
     * @param TEXT
     * @param TEXT_POSITION_X
     * @param TEXT_POSITION_Y
     * @param ROTATION_ANGLE
     * @return Glyph that is a shape of the given string rotated around it's center.
     */
    public java.awt.Shape rotateTextAroundCenter(final java.awt.Graphics2D G2, final String TEXT, final int TEXT_POSITION_X, final int TEXT_POSITION_Y, final double ROTATION_ANGLE)
    {
        final java.awt.font.FontRenderContext RENDER_CONTEXT = new java.awt.font.FontRenderContext(null, true, true);
        final java.awt.font.TextLayout TEXT_LAYOUT = new java.awt.font.TextLayout(TEXT, G2.getFont(), RENDER_CONTEXT);

        // Check if need to take the fonts descent into account
        final float DESCENT;
        MATCHES_NUMBERS.reset(TEXT);
        if (MATCHES_NUMBERS.matches())
        {
            DESCENT = TEXT_LAYOUT.getDescent();
        }
        else
        {
            DESCENT = 0;
        }
        final java.awt.geom.Rectangle2D TEXT_BOUNDS = TEXT_LAYOUT.getBounds();
        TEXT_BOUNDARY.setRect(TEXT_BOUNDS.getMinX(), TEXT_BOUNDS.getMinY(), TEXT_BOUNDS.getWidth(), TEXT_BOUNDS.getHeight() + DESCENT/2);

        final java.awt.font.GlyphVector GLYPH_VECTOR = G2.getFont().createGlyphVector(RENDER_CONTEXT, TEXT);

        final java.awt.Shape GLYPH = GLYPH_VECTOR.getOutline((int) -TEXT_BOUNDARY.getCenterX(), 2 * (int) TEXT_BOUNDARY.getCenterY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        G2.translate(TEXT_POSITION_X, TEXT_POSITION_Y + TEXT_BOUNDARY.getHeight());

        G2.rotate(Math.toRadians(ROTATION_ANGLE), -TEXT_BOUNDARY.getCenterX() + TEXT_BOUNDARY.getWidth() / 2, TEXT_BOUNDARY.getCenterY() - (TEXT_BOUNDARY.getHeight() + DESCENT) / 2);
        G2.fill(GLYPH);

        G2.setTransform(OLD_TRANSFORM);

        return GLYPH;
    }

    /**
     * Calculates the centered position of the given text in the given boundary and
     * the given graphics2d object. This is really useful when centering text on buttons or other components.
     * @param G2
     * @param BOUNDARY
     * @param TEXT
     * @return a point2d that defines the position of the given text centered in the given rectangle
     */
    public java.awt.geom.Point2D getCenteredTextPosition(final java.awt.Graphics2D G2, final java.awt.geom.Rectangle2D BOUNDARY, final String TEXT)
    {
        return getCenteredTextPosition(G2, BOUNDARY, G2.getFont(), TEXT);
    }

    /**
     * Calculates the centered position of the given text in the given boundary, with the given font and
     * the given graphics2d object. This is really useful when centering text on buttons or other components.
     * @param G2
     * @param BOUNDARY
     * @param FONT
     * @param TEXT
     * @return a point2d that defines the position of the given text centered in the given rectangle
     */
    public java.awt.geom.Point2D getCenteredTextPosition(final java.awt.Graphics2D G2, final java.awt.geom.Rectangle2D BOUNDARY, final java.awt.Font FONT, final String TEXT)
    {
        // Get the visual center of the component.
        final double CENTER_X = BOUNDARY.getWidth() / 2.0;
        final double CENTER_Y = BOUNDARY.getHeight() / 2.0;

        // Get the text boundary
        final java.awt.font.FontRenderContext RENDER_CONTEXT = G2.getFontRenderContext();
        final java.awt.font.TextLayout LAYOUT = new java.awt.font.TextLayout(TEXT, FONT, RENDER_CONTEXT);
        final java.awt.geom.Rectangle2D TEXT_BOUNDS = LAYOUT.getBounds();

        // Calculate the text position
        final double TEXT_X = CENTER_X - TEXT_BOUNDS.getWidth() / 2.0;
        final double TEXT_Y = CENTER_Y - TEXT_BOUNDS.getHeight() / 2.0 + TEXT_BOUNDS.getHeight();

        return new java.awt.geom.Point2D.Double(TEXT_X, TEXT_Y);
    }

    /**
     * This method was taken from the great book "Filthy Rich Clients"
     * from Chet Haase and Romain Guy
     *
     * Convenience method that returns a scaled instance of the
     * provided BufferedImage.
     *
     * @param IMAGE the original image to be scaled
     * @param TARGET_WIDTH the desired width of the scaled instance,
     *    in pixels
     * @param TARGET_HEIGHT the desired height of the scaled instance,
     *    in pixels
     * @param HINT one of the rendering hints that corresponds to
     *    RenderingHints.KEY_INTERPOLATION (e.g.
     *    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR,
     *    RenderingHints.VALUE_INTERPOLATION_BILINEAR,
     *    RenderingHints.VALUE_INTERPOLATION_BICUBIC)
     * @param PROGRESSIVE_BILINEAR if true, this method will use a multi-step
     *    scaling technique that provides higher quality than the usual
     *    one-step technique (only useful in down-scaling cases, where
     *    targetWidth or targetHeight is
     *    smaller than the original dimensions)
     * @return a scaled version of the original BufferedImage
     */
    public java.awt.image.BufferedImage getScaledInstance(final java.awt.image.BufferedImage IMAGE, final int TARGET_WIDTH, final int TARGET_HEIGHT, final Object HINT, final boolean PROGRESSIVE_BILINEAR)
    {
        final int TYPE = (IMAGE.getTransparency() == java.awt.Transparency.OPAQUE) ? java.awt.image.BufferedImage.TYPE_INT_RGB : java.awt.image.BufferedImage.TYPE_INT_ARGB;
        java.awt.image.BufferedImage ret = IMAGE;
        java.awt.image.BufferedImage scratchImage = null;
        java.awt.Graphics2D g2 = null;
        int width;
        int height;
        int previewWidth = ret.getWidth();
        int previewHeight = ret.getHeight();
        if (PROGRESSIVE_BILINEAR)
        {
            width = IMAGE.getWidth();
            height = IMAGE.getHeight();
        }
        else
        {
            width = TARGET_WIDTH;
            height = TARGET_HEIGHT;
        }    
        
        do
        {
            if (PROGRESSIVE_BILINEAR && width > TARGET_WIDTH)
            {
                width /= 2;
                if (width < TARGET_WIDTH)
                {
                    width = TARGET_WIDTH;
                }
            }
            
            if (PROGRESSIVE_BILINEAR && height > TARGET_HEIGHT)
            {
                height /= 2;
                if (height < TARGET_HEIGHT)
                {
                    height = TARGET_HEIGHT;
                }
            }
        
        
            if (scratchImage == null)
            {
                scratchImage = new java.awt.image.BufferedImage(width, height, TYPE);
                g2 = scratchImage.createGraphics();
            }
            
            g2.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, HINT);
            g2.drawImage(ret, 0, 0, width, height, 0, 0, previewWidth, previewHeight, null);
            previewWidth = width;
            previewHeight = height;
            
            ret = scratchImage;
        }
        while (width != TARGET_WIDTH || height != TARGET_HEIGHT);
        
        g2.dispose();
        
        if (TARGET_WIDTH != ret.getWidth() || TARGET_HEIGHT != ret.getHeight())        
        {
            scratchImage = new java.awt.image.BufferedImage(TARGET_WIDTH, TARGET_HEIGHT, TYPE);
            g2 = scratchImage.createGraphics();
            g2.drawImage(ret, 0, 0, null);
            g2.dispose();
            ret = scratchImage;
        }
        
        return ret;
    }

    /**
     * Creates a image that contains the reflection of the given sourceimage.
     * This could be useful whereever you need some eyecandy. Here we use the good working
     * standard values for opacity = 0.5f and fade out height = 0.7f.
     * @param SOURCE_IMAGE
     * @return a new buffered image that contains the reflection of the original image
     */
    public java.awt.image.BufferedImage createReflectionImage(final java.awt.image.BufferedImage SOURCE_IMAGE)
    {
        return createReflectionImage(SOURCE_IMAGE, 0.5f, 0.7f);
    }

    /**
     * Creates a image that contains the reflection of the given sourceimage.
     * This could be useful whereever you need some eyecandy.
     * @param SOURCE_IMAGE
     * @param OPACITY a good standard value is 0.5f
     * @param FADE_OUT_HEIGHT a good standard value is 0.7f
     * @return a new buffered image that contains the reflection of the original image
     */
    public java.awt.image.BufferedImage createReflectionImage(final java.awt.image.BufferedImage SOURCE_IMAGE, final float OPACITY, final float FADE_OUT_HEIGHT)
    {
        final java.awt.image.BufferedImage REFLECTION_IMAGE = new java.awt.image.BufferedImage(SOURCE_IMAGE.getWidth(), SOURCE_IMAGE.getHeight(), java.awt.image.BufferedImage.TYPE_INT_ARGB);

        final java.awt.Graphics2D G2 = REFLECTION_IMAGE.createGraphics();

        G2.translate(0, SOURCE_IMAGE.getHeight());
        G2.scale(1, -1);
        G2.drawRenderedImage(SOURCE_IMAGE, null);
        G2.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.DST_IN));
        G2.setPaint(new java.awt.GradientPaint(0, SOURCE_IMAGE.getHeight() * FADE_OUT_HEIGHT, new java.awt.Color(0.0f, 0.0f, 0.0f, 0.0f), 0, SOURCE_IMAGE.getHeight(), new java.awt.Color(0.0f, 0.0f, 0.0f, OPACITY)));
        G2.fillRect(0, 0, SOURCE_IMAGE.getWidth(), SOURCE_IMAGE.getHeight());
        G2.dispose();

        return REFLECTION_IMAGE;
    }

    /**
     * Creates a texture with a brushed metal look. The code originaly comes from Jerry Huxtable.
     * If you don't know his Java image related stuff you have to check out http://huxtable.com/
     * @param WIDTH
     * @param HEIGHT
     * @param COLOR
     * @return a buffered image that contains a brushed metal texture
     */
    public java.awt.image.BufferedImage createBrushMetalTexture(final java.awt.Color COLOR, final int WIDTH, final int HEIGHT)
    {
        final java.awt.image.BufferedImage IMAGE = new java.awt.image.BufferedImage(WIDTH, HEIGHT, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        BrushedMetalFilter metalBrush = new BrushedMetalFilter();
        if (COLOR != null)
        {
            metalBrush.setColor(COLOR.getRGB());
        }
        metalBrush.setMonochrome(true);
        metalBrush.setShine(0.3f);
        metalBrush.setRadius(5);
        return metalBrush.filter(IMAGE, IMAGE);
    }
    
    /**
     * Returns the given COLOR with the given ALPHA transparency
     * @param COLOR
     * @param ALPHA
     * @return Color with the given float transparency
     */
    public java.awt.Color setAlpha(final java.awt.Color COLOR, final float ALPHA)
    {
        return setAlpha(COLOR, (int) (255 * ALPHA));
    }

    /**
     * Return the given COLOR with the given ALPHA transparency
     * @param COLOR
     * @param ALPHA
     * @return Color with given integer transparency
     */
    public java.awt.Color setAlpha(final java.awt.Color COLOR, final int ALPHA)
    {
        return new java.awt.Color(COLOR.getRed(), COLOR.getGreen(), COLOR.getBlue(), ALPHA);
    }

    /**
     * Returns the color that equals the value from CURRENT_FRACTION in a RANGE of values
     * where the start of the RANGE equals the SOURCE_COLOR and the end of the RANGE
     * equals the DESTINATION_COLOR. In other words you could get any color in a gradient
     * between to colors by a given value.
     * @param SOURCE_COLOR
     * @param DESTINATION_COLOR
     * @param RANGE
     * @param CURRENT_FRACTION
     * @return Color that was calculated by a fraction from a range of values.
     */
    public java.awt.Color getColorFromFraction(final java.awt.Color SOURCE_COLOR, final java.awt.Color DESTINATION_COLOR, final int RANGE, final int CURRENT_FRACTION)
    {
        final float SOURCE_RED = SOURCE_COLOR.getRed() * INT_TO_FLOAT_CONST;
        final float SOURCE_GREEN = SOURCE_COLOR.getGreen() * INT_TO_FLOAT_CONST;
        final float SOURCE_BLUE = SOURCE_COLOR.getBlue() * INT_TO_FLOAT_CONST;
        final float SOURCE_ALPHA = SOURCE_COLOR.getAlpha() * INT_TO_FLOAT_CONST;

        final float DESTINATION_RED = DESTINATION_COLOR.getRed() * INT_TO_FLOAT_CONST;
        final float DESTINATION_GREEN = DESTINATION_COLOR.getGreen() * INT_TO_FLOAT_CONST;
        final float DESTINATION_BLUE = DESTINATION_COLOR.getBlue() * INT_TO_FLOAT_CONST;
        final float DESTINATION_ALPHA = DESTINATION_COLOR.getAlpha() * INT_TO_FLOAT_CONST;

        final float RED_DELTA = DESTINATION_RED - SOURCE_RED;
        final float GREEN_DELTA = DESTINATION_GREEN - SOURCE_GREEN;
        final float BLUE_DELTA = DESTINATION_BLUE - SOURCE_BLUE;
        final float ALPHA_DELTA = DESTINATION_ALPHA - SOURCE_ALPHA;

        final float RED_FRACTION = RED_DELTA / RANGE;
        final float GREEN_FRACTION = GREEN_DELTA / RANGE;
        final float BLUE_FRACTION = BLUE_DELTA / RANGE;
        final float ALPHA_FRACTION = ALPHA_DELTA / RANGE;

        return new java.awt.Color(SOURCE_RED + RED_FRACTION * CURRENT_FRACTION, SOURCE_GREEN + GREEN_FRACTION * CURRENT_FRACTION, SOURCE_BLUE + BLUE_FRACTION * CURRENT_FRACTION, SOURCE_ALPHA + ALPHA_FRACTION * CURRENT_FRACTION);
    }

    /**
     * Returns the given COLOR with the given BRIGHTNESS
     * @param COLOR
     * @param BRIGHTNESS
     * @return Color with the given brightness
     */
    public java.awt.Color setBrightness(final java.awt.Color COLOR, final float BRIGHTNESS)
    {
        final float HSB_VALUES[] = java.awt.Color.RGBtoHSB( COLOR.getRed(), COLOR.getGreen(), COLOR.getBlue(), null );
        return java.awt.Color.getHSBColor( HSB_VALUES[0], HSB_VALUES[1], BRIGHTNESS);
    }

    /**
     * Returns the given COLOR with the given SATURATION which is really useful
     * if you would like to receive a red tone that has the same brightness and hue
     * as a given blue tone.
     * @param COLOR
     * @param SATURATION
     * @return Color with a given saturation
     */
    public java.awt.Color setSaturation(final java.awt.Color COLOR, final float SATURATION)
    {
        final float HSB_VALUES[] = java.awt.Color.RGBtoHSB( COLOR.getRed(), COLOR.getGreen(), COLOR.getBlue(), null );
        return java.awt.Color.getHSBColor( HSB_VALUES[0], SATURATION, HSB_VALUES[2]);
    }

    /**
     * Returns the given COLOR with the given HUE
     * @param COLOR
     * @param HUE
     * @return Color with a given hue
     */
    public java.awt.Color setHue(final java.awt.Color COLOR, final float HUE)
    {
        final float HSB_VALUES[] = java.awt.Color.RGBtoHSB( COLOR.getRed(), COLOR.getGreen(), COLOR.getBlue(), null );
        return java.awt.Color.getHSBColor( HUE, HSB_VALUES[1], HSB_VALUES[2]);
    }

    /**
     * Returns the seven segment font "lcd.ttf" if it is available.
     * Usualy it should be no problem because it will be delivered in the package but
     * if there is a problem it will return the standard font which is verdana.
     * @return Font with fontface from lcd.ttf (if available)
     */
    public java.awt.Font getDigitalFont()
    {
        if (digitalFont == null)
        {
            digitalFont = standardFont;
        }
        return this.digitalFont.deriveFont(24).deriveFont(java.awt.Font.PLAIN);
    }

    /**
     * Returns the standard font which is verdana.
     * @return Font that is defined as standard
     */
    public java.awt.Font getStandardFont()
    {
        return this.standardFont;
    }
    // 
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy