adjustContrast method
Adjusts the color to a specific contrast target.
Parameters:
target
The target contrast for the color adjustment.on
The color to compare contrast against. Defaults to Colors.white.maxIterations
The maximum number of iterations for color adjustment. Defaults to 1000 iterations.epsilon
The difference tolerance for the contrast ratio. Defaults to 0.1.
Returns:
- A new color with adjusted contrast close to the target contrast.
Implementation
Color adjustContrast({
required Color on,
required double target,
int maxIterations = 1000,
double epsilon = 0.1,
}) {
int iteration = 0;
Color adjustedColor = this;
double adjustmentValue;
while (iteration < maxIterations) {
final currentContrast = adjustedColor.contrastRatio(on);
if (currentContrast == target || (currentContrast - target).abs() < epsilon) {
break;
}
final hslColor = HSLColor.fromColor(adjustedColor);
adjustmentValue = (currentContrast - target).abs() * 0.02;
var newLightness =
(currentContrast < target) ? hslColor.lightness - adjustmentValue : hslColor.lightness + adjustmentValue;
newLightness = newLightness.clamp(0.0, 1.0);
adjustedColor = hslColor.withLightness(newLightness).toColor();
iteration++;
}
return adjustedColor;
}