Changes the opacity of a color - Java 2D Graphics

Java examples for 2D Graphics:Color Alpha

Description

Changes the opacity of a color

Demo Code

/*//w  w w. ja  va 2 s.c o  m
 * Copyright (c) 2008 Pierre Dragicevic <dragice@lri.fr>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

import java.awt.Color;

public class Main {
    /**
     * Changes the opacity of a color
     */
    public static Color multiplyAlpha(Color c0, float alpha) {
        if (alpha == 1)
            return c0;
        float r0 = c0.getRed() / 255f;
        float g0 = c0.getGreen() / 255f;
        float b0 = c0.getBlue() / 255f;
        float a0 = c0.getAlpha() / 255f;
        return new Color(r0, g0, b0, bound01(a0 * alpha));
    }

    private static float bound01(float x) {
        if (x < 0)
            x = 0;
        if (x > 1)
            x = 1;
        return x;
    }
}

Related Tutorials