返回顶部
首页 > 资讯 > 后端开发 > Python >Java基础之颜色工具类(超详细注释)
  • 800
分享到

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

2024-04-02 19:04:59 800人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

颜色工具类(超详细注释) 设置属性值自动格式化rgb值和十六进制颜色值。 import java.util.HashMap; import java.util.Map; pub

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

设置属性值自动格式化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";
    }

    
    public Color(Integer red, Integer green, Integer blue){
        // 调用 [通过RGBA四值初始化]
        this(red, green, blue, 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);
    }

    
    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\".");
        }
    }

    
    public Integer getRed(){
        return this.red;
    }

    
    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();
    }

    
    public Integer getGreen(){
        return this.green;
    }

    
    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();
    }

    
    public Integer getBlue(){
        return this.blue;
    }

    
    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();
    }

    
    public String getHexRed(){
        return this.hexRed;
    }

    
    public void setHexRed(String hexRed) {
        // 去空格、转大写
        hexRed = hexRed.replaceAll("\\s*", "").toUpperCase();

        // 检查颜色值
        checkHexColorString(hexRed,"HexRed");

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

        // 刷新
        this.refresh();
    }

    
    public String getHexGreen(){
        return this.hexGreen;
    }

    
    public void setHexGreen(String hexGreen) {
        // 去空格、转大写
        hexGreen = hexGreen.replaceAll("\\s*", "").toUpperCase();

        // 检查颜色值
        checkHexColorString(hexGreen,"HexGreen");

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

        // 刷新
        this.refresh();
    }

    
    public String getHexBlue(){
        return this.hexBlue;
    }

    
    public void setHexBlue(String hexBlue) {
        // 去空格、转大写
        hexBlue = hexBlue.replaceAll("\\s*", "").toUpperCase();

        // 检查颜色值
        checkHexColorString(hexBlue,"HexBlue");

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

        // 刷新
        this.refresh();
    }

    
    public Double getAlpha(){
        return this.alpha;
    }

    
    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();
    }

    
    public String getRgb(){
        return this.rgb;
    }

    
    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();
    }

    
    public String getRgba(){
        return this.rgba;
    }

    
    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();
    }

    
    public String getHex(){
        return this.hex;
    }

    
    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();
    }


    
    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};
    }

    
    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};
    }

    
    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};
    }

    
    private synchronized String generateRgb(){
        // 准备结果
        String result = "rgb(";

        // 添加红色值
        result += this.getRed();
        result += ", ";
        // 添加绿色值
        result += this.getGreen();
        result += ", ";
        // 添加蓝色值
        result += this.getBlue();
        result += ")";

        // 返回结果
        return result;
    }

    
    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;
    }

    
    private synchronized String generateHex(){
        // 准备结果
        String result = "#";

        // 添加红色值
        result += this.getHexRed();
        // 添加绿色值
        result += this.getHexGreen();
        // 添加蓝色值
        result += this.getHexBlue();

        // 返回结果
        return result;
    }

    
    private String normalToHex(Integer number){
        // 十进制转十六进制
        String hexNumber = Integer.toHexString(number).toUpperCase();

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

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

    
    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;
    }

    
    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();
    }

    
    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颜色工具类内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Java基础之颜色工具类(超详细注释)

本文链接: https://lsjlt.com/news/124752.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
  • Java基础之颜色工具类(超详细注释)
    颜色工具类(超详细注释) 设置属性值自动格式化rgb值和十六进制颜色值。 import java.util.HashMap; import java.util.Map; pub...
    99+
    2024-04-02
  • Java基础之颜色工具类的示例分析
    这篇文章主要介绍Java基础之颜色工具类的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!常用的java框架有哪些1.SpringMVC,Spring Web MVC是一种基于Java的实现了Web MVC设计...
    99+
    2023-06-14
  • Java基础类之ArrayUtils工具类详解
    目录1、引入pom依赖2、ArrayUtils中的方法:3、举例总结1、引入pom依赖 <!-- https://mvnrepository.com/artifact/o...
    99+
    2024-04-02
  • Java 基础--Arrays工具类详解
    目录1、数组转换成字符串2、数组转换成集合(1)asList(2)stream 流操作(3)Collections.addAll()3、对数组进行升序排列4、判断数组是否相等5、所有...
    99+
    2024-04-02
  • Java基础之数组超详细知识总结
    目录一、一维数组二、二维数组三、总结一、一维数组 1、Java语言中的数组是一种 引用数据类型。不属于基本数据类型。数组的父类是 Object。 2、数组实际上是一个容器,可以同时容...
    99+
    2024-04-02
  • Java基础详解之集合框架工具Collections
    目录一、Collections二、Collections中的常见方法三、Aarrays:用于对数组操作的工具类四、二分查找过程中的默认比较器五、集合转化为数组六、增强for循环七、关...
    99+
    2024-04-02
  • Java请求Http接口-OkHttp(超详细-附带工具类)
    简介:OkHttp是一个默认有效的HTTP客户端,有效地执行HTTP可以加快您的负载并节省带宽,如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6...
    99+
    2023-09-28
    java http okhttp
  • Java请求Http接口-hutool的HttpUtil(超详细-附带工具类)
    概述 HttpUtil是应对简单场景下Http请求的工具类封装,此工具封装了HttpRequest对象常用操作,可以保证在一个方法之内完成Http请求。 此模块基于JDK的HttpUrlConnect...
    99+
    2023-09-04
    java http 开发语言
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作