UID 1712152 性别 保密 经验 EP 铁粒 粒 回帖 0 主题 精华 在线时间 小时 注册时间 2024-5-23 最后登录 1970-1-1
package org.example ;import java.awt.Color ;public class ColorGradient {
public enum GradientType {
LINEAR ,
HSV }
public static Color interpolate (GradientType type , Color color1 , Color color2 , float t ) {
switch (type ) {
case LINEAR :
return linearInterpolation (color1 , color2 , t );
case HSV :
return hsvInterpolation (color1 , color2 , t );
default :
throw new IllegalArgumentException("Unknown gradient type: " + type );
}
}
private static Color linearInterpolation (Color color1 , Color color2 , float t ) {
int r = (int ) (color1 .getRed() + (color2 .getRed() - color1 .getRed()) * t );
int g = (int ) (color1 .getGreen() + (color2 .getGreen() - color1 .getGreen()) * t );
int b = (int ) (color1 .getBlue() + (color2 .getBlue() - color1 .getBlue()) * t );
int a = (int ) (color1 .getAlpha() + (color2 .getAlpha() - color1 .getAlpha()) * t );
return new Color(r , g , b , a );
}
private static Color hsvInterpolation (Color color1 , Color color2 , float t ) {
float [] hsv1 = Color .RGBtoHSB (color1 .getRed(), color1 .getGreen(), color1 .getBlue(), null );
float [] hsv2 = Color .RGBtoHSB (color2 .getRed(), color2 .getGreen(), color2 .getBlue(), null );
float h = (hsv1 [0 ] + (hsv2 [0 ] - hsv1 [0 ]) * t );
float s = (hsv1 [1 ] + (hsv2 [1 ] - hsv1 [1 ]) * t );
float v = (hsv1 [2 ] + (hsv2 [2 ] - hsv1 [2 ]) * t );
return Color .getHSBColor (h , s , v );
}
public static void main (String [] args ) {
Color color1 = new Color(255 , 0 , 0 ); // Red Color color2 = new Color(0 , 0 , 255 ); // Blue float t = 0.5f ; // Midpoint Color interpolatedColor = interpolate (GradientType .LINEAR , color1 , color2 , t );
System .out .println("Linear Interpolation: " + interpolatedColor );
interpolatedColor = interpolate (GradientType .HSV , color1 , color2 , t );
System .out .println("HSV Interpolation: " + interpolatedColor );
}
}
以上代码实现了线性渐变和HSV渐变两种算法,HSV渐变看起来会更加平滑