!1257 防止设置色差过大,导致循环次数过多等优化

Merge pull request !1257 from czc/v5-dev
This commit is contained in:
Looly
2024-08-09 04:06:30 +00:00
committed by Gitee
4 changed files with 86 additions and 7 deletions

View File

@@ -1,6 +1,7 @@
package cn.hutool.core.img;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
@@ -178,6 +179,9 @@ public class ColorUtil {
* @since 5.8.30
*/
public static Color randomColor(Color compareColor,int minDistance) {
// 注意minDistance太大会增加循环次数保证至少1/3的概率生成成功
Assert.isTrue(minDistance < maxDistance(compareColor) / 3 * 2,
"minDistance is too large, there are too few remaining colors!");
Color color = randomColor();
while (computeColorDistance(compareColor,color) < minDistance) {
color = randomColor();
@@ -195,6 +199,24 @@ public class ColorUtil {
return randomColor(null);
}
/**
* 计算给定点与其他点之间的最大可能距离。
*
* @param color 指定颜色
* @return 其余颜色与color的最大距离
* @since 6.0.0-M16
*/
public static int maxDistance(final Color color) {
if (null == color) {
// (0,0,0)到(256,256,256)的距离约等于442.336
return 443;
}
final int maxX = RGB_COLOR_BOUND - 2 * color.getRed();
final int maxY = RGB_COLOR_BOUND - 2 * color.getGreen();
final int maxZ = RGB_COLOR_BOUND - 2 * color.getBlue();
return (int)Math.sqrt(maxX * maxX + maxY * maxY + maxZ * maxZ);
}
/**
* 计算两个颜色之间的色差,按三维坐标距离计算
*
@@ -205,7 +227,8 @@ public class ColorUtil {
*/
public static int computeColorDistance(Color color1, Color color2) {
if (null == color1 || null == color2) {
return 0;
// (0,0,0)到(256,256,256)的距离约等于442.336
return 443;
}
return (int) Math.sqrt(Math.pow(color1.getRed() - color2.getRed(), 2)
+ Math.pow(color1.getGreen() - color2.getGreen(), 2)

View File

@@ -101,6 +101,23 @@ public class GraphicsUtil {
return drawString(g, str, font, null, width, height, compareColor, minColorDistance);
}
/**
* 绘制字符串,使用随机颜色,并且与背景颜色保持一定色差,默认抗锯齿
*
* @param g {@link Graphics}画笔
* @param str 字符串
* @param font 字体
* @param width 字符串总宽度
* @param height 字符串背景高度
* @param backgroundColor 背景颜色
* @return 画笔对象
* @since 4.5.10
*/
public static Graphics drawStringColourful(Graphics g, String str, Font font, int width, int height, Color backgroundColor) {
// 默认色差为最大色差的1/2
return drawString(g, str, font, null, width, height, backgroundColor, ColorUtil.maxDistance(backgroundColor) / 2);
}
/**
* 绘制字符串,默认抗锯齿
*

View File

@@ -2237,6 +2237,17 @@ public class ImgUtil {
return ColorUtil.randomColor(compareColor,minDistance);
}
/**
* 生成随机颜色,与指定颜色有一定的区分度
*
* @param compareColor 比较颜色
* @return 与指定颜色有一定的区分度的随机颜色,默认是最大可能的三维距离的一半
* @since 5.8.30
*/
public static Color randomColor(Color compareColor) {
return ColorUtil.randomColor(compareColor,ColorUtil.maxDistance(compareColor) / 2);
}
/**
* 生成随机颜色
*