What's the best way to “round” a Color object to the nearest Color Constant?

后端 未结 3 1899
-上瘾入骨i
-上瘾入骨i 2021-02-04 09:37

I will be retrieving the exact color of a pixel and would like to relate that exact color to a constant like Color.blue. Is there an easy way to \"round\" to the n

3条回答
  •  心在旅途
    2021-02-04 10:02

    Probably the best way would be to loop over every constant, and comparing their respective RGB channels (getRed, getGreen, getBlue). Keep track of the one that is closest.

    Color color = new Color(...);
    Color[] constantColors = new Color[] { Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow };
    Color nearestColor = null;
    Integer nearestDistance = new Integer(Integer.MAX_VALUE);
    
    for (Color constantColor : constantColors) {
        if (nearestDistance > Math.sqrt(
                Math.pow(color.getRed() - constantColor.getRed(), 2)
                - Math.pow(color.getGreen() - constantColor.getGreen(), 2)
                - Math.pow(color.getBlue() - constantColor.getBlue(), 2)
            )
        ) {
            nearestColor = color;
        }
    }
    

    No, you can't add color constants to the class, but you can create a class of your own to hold constants.

    class MyColors {
        public static final Color heliotrope = new Color(...);
    }
    

    Edit: added difference algorithm, thanks to @Ted's link.

提交回复
热议问题