欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java基础之颜色工具类(超详细注释)

程序员文章站 2022-04-03 18:31:40
颜色工具类(超详细注释)设置属性值自动格式化rgb值和十六进制颜色值。import java.util.hashmap;import java.util.map;public class color{...

颜色工具类(超详细注释)

设置属性值自动格式化rgb值和十六进制颜色值。

import java.util.hashmap;
import java.util.map;

public class color{
    private final string[] hex_letters = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    private double alpha;// 透明度(0.0 ~ 1.0)

    private integer red; // 红色值(0~255)
    private integer green; // 绿色值(0~255)
    private integer blue; // 蓝色值(0~255)
    private string rgb; // rgb值;格式:rgb(red, green, blue)
    private string rgba; // rgba值;格式:rgb(red, green, blue, alpha)

    private string hexred; // 十六进制红色值(00-ff)
    private string hexgreen; // 十六进制绿色值(00-ff)
    private string hexblue; // 十六进制蓝色值(00-ff)
    private string hex; // 十六进制颜色值;格式:#hexredhexgreenhexblue

    /**
     * 无参构造器
     * 默认黑色不透明
     */
    public color(){
        this.red = 0;
        this.green = 0;
        this.blue = 0;
        this.alpha = 1.0;
        this.hexred = "00";
        this.hexgreen = "00";
        this.hexblue = "00";
        this.rgb = "rgb(0, 0, 0)";
        this.rgba = "rgba(0, 0, 0, 1.0)";
        this.hex = "#000000";
    }

    /**
     * 通过rgb三值初始化
     *
     * @param red 红色值(0~255)
     * @param green 绿色值(0~255)
     * @param blue 蓝色值(0~255)
     */
    public color(integer red, integer green, integer blue){
        // 调用 [通过rgba四值初始化]
        this(red, green, blue, 1.0);
    }

    /**
     * 通过rgba四值初始化
     *
     * @param red 红色值(0~255)
     * @param green 绿色值(0~255)
     * @param blue 蓝色值(0~255)
     * @param alpha 透明度(0.0 ~ 1.0)
     */
    public color(integer red, integer green, integer blue, double alpha){
        // 设置透明度
        this.setalpha(alpha);

        // 设置rgb值
        this.setred(red);
        this.setgreen(green);
        this.setblue(blue);
    }

    /**
     * 通过颜色字符串初始化
     * @param colorstr 颜色字符串;格式为:rgb(red,green,blue) 或 rgba(red,green,blue,alpha) 或 #hexredhexgreenhexblue
     */
    public color(string colorstr){
        // 字符串转大写、去空格
        colorstr = colorstr.replaceall("\\s*", "").touppercase();

        if(colorstr.startswith("#")) {
            this.alpha = 1.0;
            this.sethex(colorstr);
        } else if(colorstr.startswith("rgb(") && colorstr.endswith(")")) {
            this.alpha = 1.0;
            this.setrgb(colorstr);
        }else if (colorstr.startswith("rgba(") && colorstr.endswith(")")) {
            this.setrgba(colorstr);
        }else {
            throw new colorparseexception("color parsing failed, please check color code format. the format is: \"rgb(red,green,blue)\" or \"rgba(red,green,blue,alpha)\" or \"#hexredhexgreenhexblue\".");
        }
    }

    /**
     * 获取红色值
     * @return 红色值(0~255)
     */
    public integer getred(){
        return this.red;
    }

    /**
     * 设置红色值
     * @param red 红色值(0~255)
     */
    public void setred(integer red) {
        // 检查颜色值
        if(red < 0 || red > 255)
            throw new coloroutofrangeexception("red out of range, please set value in 0 ~ 255.");

        // 设置红色值
        this.red = red;
        // 红色值转十六进制红色值,并设置十六进制红色值
        this.hexred = this.normaltohex(red);

        // 刷新
        this.refresh();
    }

    /**
     * 获取绿色值
     * @return 绿色值(0~255)
     */
    public integer getgreen(){
        return this.green;
    }

    /**
     * 设置绿色值
     * @param green 绿色值(0~255)
     */
    public void setgreen(integer green) {
        // 检查颜色值
        if(green < 0 || green > 255)
            throw new coloroutofrangeexception("green out of range, please set value in 0 ~ 255.");

        // 设置绿色值
        this.green = green;
        // 绿色值转十六进制红色值,并设置十六进制绿色值
        this.hexgreen = this.normaltohex(green);

        // 刷新
        this.refresh();
    }

    /**
     * 获取蓝色值
     * @return 蓝色值(0~255)
     */
    public integer getblue(){
        return this.blue;
    }

    /**
     * 设置蓝色值
     * @param blue 蓝色值(0~255)
     */
    public void setblue(integer blue) {
        // 检查颜色值
        if(blue < 0 || blue > 255)
            throw new coloroutofrangeexception("blue out of range, please set value in 0 ~ 255.");

        // 设置蓝色值
        this.blue = blue;
        // 绿色值转十六进制红色值,并设置十六进制绿色值
        this.hexblue = this.normaltohex(blue);

        // 刷新
        this.refresh();
    }

    /**
     * 获取十六进制红色值
     * @return 十六进制红色值(00-ff)
     */
    public string gethexred(){
        return this.hexred;
    }

    /**
     * 设置十六进制红色值
     * @param hexred 十六进制红色值(00-ff)
     */
    public void sethexred(string hexred) {
        // 去空格、转大写
        hexred = hexred.replaceall("\\s*", "").touppercase();

        // 检查颜色值
        checkhexcolorstring(hexred,"hexred");

        // 设置十六进制红色值
        this.hexred = hexred;
        // 设置红色值
        this.red = hextonormal(hexred);

        // 刷新
        this.refresh();
    }

    /**
     * 获取十六进制绿色值
     * @return 十六进制绿色值(00-ff)
     */
    public string gethexgreen(){
        return this.hexgreen;
    }

    /**
     * 设置十六进制绿色值
     * @param hexgreen 十六进制绿色值(00-ff)
     */
    public void sethexgreen(string hexgreen) {
        // 去空格、转大写
        hexgreen = hexgreen.replaceall("\\s*", "").touppercase();

        // 检查颜色值
        checkhexcolorstring(hexgreen,"hexgreen");

        // 设置十六进制绿色值
        this.hexgreen = hexgreen;
        // 设置绿色值
        this.green = hextonormal(hexgreen);

        // 刷新
        this.refresh();
    }

    /**
     * 获取十六进制蓝色值
     * @return 十六进制蓝色值(00-ff)
     */
    public string gethexblue(){
        return this.hexblue;
    }

    /**
     * 设置十六进制蓝色值
     * @param hexblue 十六进制蓝色值(00-ff)
     */
    public void sethexblue(string hexblue) {
        // 去空格、转大写
        hexblue = hexblue.replaceall("\\s*", "").touppercase();

        // 检查颜色值
        checkhexcolorstring(hexblue,"hexblue");

        // 设置十六进制蓝色值
        this.hexblue = hexblue;
        // 设置蓝色值
        this.blue = hextonormal(hexblue);

        // 刷新
        this.refresh();
    }

    /**
     * 获取透明度
     * @return 透明度(0.0 ~ 1.0)
     */
    public double getalpha(){
        return this.alpha;
    }

    /**
     * 设置透明度
     * @param alpha 透明度(0.0 ~ 1.0)
     */
    public void setalpha(double alpha) {
        // 检查透明度
        if(alpha < 0 || alpha > 1)
            throw new coloroutofrangeexception("alpha out of range, please set value in 0.0 ~ 1.0 and keep one decimal place.");
        // 检查小数点
        string[] alphasplit = alpha.tostring().split("\\.");
        if(alphasplit.length > 1)
            if(alphasplit[1].length() > 1)
                throw new coloroutofrangeexception("alpha out of range, please set value in 0.0 ~ 1.0 and keep one decimal place.");

        // 设置透明度
        this.alpha = alpha;

        // 刷新
        this.refresh();
    }

    /**
     * 获取rgb值
     * @return rgb值;格式:rgb(red, green, blue)
     */
    public string getrgb(){
        return this.rgb;
    }

    /**
     * 设置rgb值
     * @param rgb rgb值;格式:rgb(red, green, blue)
     */
    public void setrgb(string rgb) {
        // 解析rgb字符串
        integer[] rgbarray = parsergb(rgb);

        // 设置颜色值
        this.setred(rgbarray[0]);
        this.setgreen(rgbarray[1]);
        this.setblue(rgbarray[2]);

        // 设置十六进制颜色值
        this.sethexred(this.normaltohex(this.getred()));
        this.sethexgreen(this.normaltohex(this.getgreen()));
        this.sethexblue(this.normaltohex(this.getblue()));

        // 刷新
        this.refresh();
    }

    /**
     * 获取rgba值
     * @return rgba值;格式:rgba(red, green, blue, alpha)
     */
    public string getrgba(){
        return this.rgba;
    }

    /**
     * 设置rgba值
     * @param rgba rgba值;格式:rgba(red, green, blue, alpha)
     */
    public void setrgba(string rgba) {
        // 解析rgb字符串
        double[] rgbaarray = parsergba(rgba);

        // 设置颜色值
        this.setred((int)(double)rgbaarray[0]);
        this.setgreen((int)(double)rgbaarray[1]);
        this.setblue((int)(double)rgbaarray[2]);
        this.setalpha(rgbaarray[3]);

        // 设置十六进制颜色值
        this.sethexred(this.normaltohex(this.getred()));
        this.sethexgreen(this.normaltohex(this.getgreen()));
        this.sethexblue(this.normaltohex(this.getblue()));

        // 刷新
        this.refresh();
    }

    /**
     * 获取十六进制颜色值
     * @return 十六进制颜色值;格式:#hexredhexgreenhexblue
     */
    public string gethex(){
        return this.hex;
    }

    /**
     * 设置hex值
     * @param hex 十六进制颜色值;格式:#hexredhexgreenhexblue
     */
    public void sethex(string hex) {
        // 解析hex字符串
        string[] hexarray = parsehex(hex);

        // 设置十六进制颜色值
        this.sethexred(hexarray[0]);
        this.sethexgreen(hexarray[1]);
        this.sethexblue(hexarray[2]);

        // 设置颜色值
        this.setred(this.hextonormal(this.gethexred()));
        this.setgreen(this.hextonormal(this.gethexgreen()));
        this.setblue(this.hextonormal(this.gethexblue()));

        // 刷新
        this.refresh();
    }


    /**
     * 解析rgb字符串
     * @param rgb rgb值;格式:rgb(red, green, blue)
     * @return 颜色值数组;0: red; 1: green; 2: blue;
     */
    private integer[] parsergb(string rgb){
        // 去空格、转大写
        rgb = rgb.replaceall("\\s*", "").touppercase();

        // 检查是否为“rgb(”开头、“)”结束
        if(rgb.startswith("rgb(") && rgb.endswith(")"))
            rgb = rgb.substring(4, rgb.length()-1);

        // rgb字符串数组 通过“,”分割
        string[] rgbstrarray = rgb.split(",");

        // 判断数组长度是否小于1
        if(rgbstrarray.length < 1)
            throw new colorparseexception("rgb parsing failed, please check rgb format. the format is: \"rgb(red,green,blue)\" or \"red,green,blue\".");

        // string转int
        int red = integer.parseint(rgbstrarray[0]);
        int green = integer.parseint(rgbstrarray[1]);
        int blue = integer.parseint(rgbstrarray[2]);

        // 返回rgb颜色数组
        return new integer[]{red, green, blue};
    }

    /**
     * 解析rgba字符串
     * @param rgba rgba值;格式:rgba(red, green, blue, alpha)
     * @return 颜色值数组;0: red; 1: green; 2: blue; 3: alpha;
     */
    private double[] parsergba(string rgba){
        // 去空格、转大写
        rgba = rgba.replaceall("\\s*", "").touppercase();

        // 检查是否为“rgba(”开头、“)”结束
        if(rgba.startswith("rgba(") && rgba.endswith(")"))
            rgba = rgba.substring(5, rgba.length()-1);

        // rgb字符串数组 通过“,”分割
        string[] rgbastrarray = rgba.split(",");

        // 判断数组长度是否小于1
        if(rgbastrarray.length < 1)
            throw new colorparseexception("rgba parsing failed, please check rgba format. the format is: \"rgba(red,green,blue,alpha)\" or \"red,green,blue,alpha\".");

        // string转double
        double red = double.parsedouble(rgbastrarray[0]);
        double green = double.parsedouble(rgbastrarray[1]);
        double blue = double.parsedouble(rgbastrarray[2]);
        double alpha = double.parsedouble(rgbastrarray[3]);

        // 返回rgba颜色数组
        return new double[]{red, green, blue, alpha};
    }

    /**
     * 解析hex字符串
     * @param hex 十六进制颜色值
     * @return 颜色值数组;0: hexred; 1: hexgreen; 2: hexblue;
     */
    private string[] parsehex(string hex){
        // 字符串去空格、转大写
        hex = hex.replaceall("\\s*", "").touppercase();

        // 去起始“#”
        if(hex.startswith("#"))
            hex = hex.substring(1);

        // 声明颜色值
        string hexred;
        string hexgreen;
        string hexblue;

        // 检查字符串长度
        if(hex.length() == 3){
            // 取出颜色值
            hexred = hex.substring(0, 1);
            hexgreen = hex.substring(1, 2);
            hexblue = hex.substring(2);

            // 补全hexcolor
            hexred += hexred;
            hexgreen += hexgreen;
            hexblue += hexblue;
        }else if(hex.length() == 6){
            // 取出颜色值
            hexred = hex.substring(0, 2);
            hexgreen = hex.substring(2, 4);
            hexblue = hex.substring(4);
        }else{
            throw new colorparseexception("hex color parsing failed, please check hex color format. the format is: \"#hexcolor\" or \"hexcolor\", examples: \"#ffffff\" or \"#fff\" or \"ffffff\" or \"fff\".");
        }

        // 返回hex颜色数组
        return new string[]{hexred, hexgreen, hexblue};
    }

    /**
     * 生成rgb值
     * @return rgb值;格式:rgb(red, green, blue)
     */
    private synchronized string generatergb(){
        // 准备结果
        string result = "rgb(";

        // 添加红色值
        result += this.getred();
        result += ", ";
        // 添加绿色值
        result += this.getgreen();
        result += ", ";
        // 添加蓝色值
        result += this.getblue();
        result += ")";

        // 返回结果
        return result;
    }

    /**
     * 生成rgba值
     * @return rgba值;格式:rgb(red, green, blue, alpha)
     */
    private synchronized string generatergba(){
        // 准备结果
        string result = "rgba(";

        // 添加红色值
        result += this.getred();
        result += ", ";
        // 添加绿色值
        result += this.getgreen();
        result += ", ";
        // 添加蓝色值
        result += this.getblue();
        result += ", ";
        // 添加透明度
        result += this.getalpha();
        result += ", ";

        // 返回结果
        return result;
    }

    /**
     * 生成十六进制值
     * @return 十六进制值;格式:#hexredhexgreenhexblue
     */
    private synchronized string generatehex(){
        // 准备结果
        string result = "#";

        // 添加红色值
        result += this.gethexred();
        // 添加绿色值
        result += this.gethexgreen();
        // 添加蓝色值
        result += this.gethexblue();

        // 返回结果
        return result;
    }

    /**
     * 十进制转十六进制
     * @param number 十进制数
     * @return 十六进制字符串
     */
    private string normaltohex(integer number){
        // 十进制转十六进制
        string hexnumber = integer.tohexstring(number).touppercase();

        // 检查十六进制字符串长度
        if(hexnumber.length() == 1) // 一位
            hexnumber = 0 + hexnumber; // 前位+0

        // 返回十六进制字符串
        return hexnumber;
    }

    /**
     * 十六进制转十进制
     * @param hexstr 十六进制字符串
     * @return 十进制数
     */
    private integer hextonormal(string hexstr) {
        // 去空格转大写
        hexstr = hexstr.replaceall("\\s*", "");

        // 准备结果
        int result = 0;

        // 十六进制字母集合
        map<string, integer> hexlettersmap = new hashmap<>();
        // 十六进制字符填充至集合
        for (int i = 0; i < hex_letters.length; i++) {
            hexlettersmap.put(hex_letters[i], i);
        }

        // 将十六进制字符串转为数组
        string[] hexstrarray = new string[hexstr.length()];
        for(int i = 0; i < hexstrarray.length; i++){
            hexstrarray[i] = hexstr.substring(i, i+1);
        }

        // 转十进制数
        for(int i = 0; i < hexstrarray.length; i++){
            result += hexlettersmap.get(hexstrarray[i]) * math.pow(16, hexstrarray.length - 1 - i);
        }

        // 返回结果
        return result;
    }

    /**
     * 检查十六进制颜色字符串(两位:00~ff)
     * @param hexstr 十六进制字符串(00~ff)
     * @param errorfieldname 发生错误的字段名
     */
    private void checkhexcolorstring(string hexstr, string errorfieldname){
        // 去空格,转大写
        hexstr = hexstr.replaceall("\\s*", "").touppercase();

        // 截取字符
        string firstletter;
        string secondletter;

        // 检查格式
        if(hexstr.length() == 1){
            firstletter = secondletter = hexstr;
        }else if(hexstr.length() == 2){
            firstletter = hexstr.substring(0,1);
            secondletter = hexstr.substring(1);
        }else{
            throw new coloroutofrangeexception(errorfieldname + " out of range, please set value in 00 ~ ff.");
        }

        // 字符正确标识
        boolean firstright = false;
        boolean secondright = false;

        // 检查第一个字符
        for (string letter : hex_letters) {
            if(letter.equals(firstletter)){
                firstright = true;
                break;
            }
        }

        // 检查第二个字符
        for (string letter : hex_letters) {
            if(letter.equals(secondletter)){
                secondright = true;
                break;
            }
        }

        // 判断是否全部正确
        if(!firstright || !secondright)
            throw new coloroutofrangeexception(errorfieldname + " out of range, please set value in 00 ~ ff.");
    }

    /**
     * 刷新
     */
    private void refresh(){
        // 生成并设置rgb值
        this.rgb = this.generatergb();
        // 生成并设置rgba值
        this.rgba = this.generatergba();
        // 生成并设置十六进制颜色值
        this.hex = this.generatehex();
    }

    /**
     * 对象转字符串
     * @return 字符串
     */
    public string tostring(){
        return "color: {" +
                "\n\tred: " + this.getred() +
                ",\n\tgreen: " + this.getgreen() +
                ",\n\tblue: " + this.getblue() +
                ",\n\talpha: " + this.getalpha() +
                ",\n\trgb: " + this.getrgb() +
                ",\n\trgba: " + this.getrgba() +
                ",\n\thexred: " + this.gethexred() +
                ",\n\thexgreen: " + this.gethexgreen() +
                ",\n\thexblue: " + this.gethexblue() +
                ",\n\thex: " + this.gethex() +
                "\n}";
    }

    /**
     * 颜色超出范围异常
     */
    public static class coloroutofrangeexception extends runtimeexception{
        public coloroutofrangeexception(string message) {
            super(message);
        }
    }

    /**
     * 颜色解析异常
     */
    public static class colorparseexception extends runtimeexception{
        public colorparseexception(string message) {
            super(message);
        }
    }
}

到此这篇关于java基础之颜色工具类(超详细注释)的文章就介绍到这了,更多相关java颜色工具类内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!