wp_tinycolor_bound01()
云策文档标注
概述
wp_tinycolor_bound01() 是一个已弃用的 WordPress 函数,用于将输入值从 [0, n] 范围映射到 [0, 1] 范围。它基于 TinyColor 库的简化实现,主要用于颜色处理中的数值标准化。
关键要点
- 函数 wp_tinycolor_bound01( $n, $max ) 接受两个参数:$n(数值或字符串)和 $max(整数上限值),返回一个浮点数在 [0, 1] 范围内。
- 该函数已从 WordPress 6.3.0 版本起弃用,开发者应避免在新代码中使用,并考虑替代方案。
- 函数内部处理包括边界限制(使用 min 和 max)、百分比自动转换(如 '100%' 转换为数值)和浮点数舍入误差处理。
- 相关函数包括 wp_tinycolor_rgb_to_rgb() 和 wp_tinycolor_hsl_to_rgb(),均用于颜色转换。
代码示例
function wp_tinycolor_bound01( $n, $max ) {
_deprecated_function( __FUNCTION__, '6.3.0' );
if ( 'string' === gettype( $n ) && str_contains( $n, '.' ) && 1 === (float) $n ) {
$n = '100%';
}
$n = min( $max, max( 0, (float) $n ) );
// Automatically convert percentage into number.
if ( 'string' === gettype( $n ) && str_contains( $n, '%' ) ) {
$n = (int) ( $n * $max ) / 100;
}
// Handle floating point rounding errors.
if ( ( abs( $n - $max ) < 0.000001 ) ) {
return 1.0;
}
return ( $n % $max ) / (float) $max;
}注意事项
- 由于函数已弃用,建议开发者检查相关代码并迁移到未弃用的替代方法,以避免未来兼容性问题。
- 函数使用 _deprecated_function() 来标记弃用状态,调用时会触发弃用通知。
- 参数 $n 支持多种类型(如数字或字符串),包括百分比格式,函数会自动处理转换。
原文内容
Takes input from [0, n] and returns it as [0, 1].
Description
Direct port of TinyColor’s function, lightly simplified to maintain consistency with TinyColor.
Parameters
$nmixedrequired-
Number of unknown type.
$maxintrequired-
Upper value of the range to bound to.
Source
function wp_tinycolor_bound01( $n, $max ) {
_deprecated_function( __FUNCTION__, '6.3.0' );
if ( 'string' === gettype( $n ) && str_contains( $n, '.' ) && 1 === (float) $n ) {
$n = '100%';
}
$n = min( $max, max( 0, (float) $n ) );
// Automatically convert percentage into number.
if ( 'string' === gettype( $n ) && str_contains( $n, '%' ) ) {
$n = (int) ( $n * $max ) / 100;
}
// Handle floating point rounding errors.
if ( ( abs( $n - $max ) < 0.000001 ) ) {
return 1.0;
}
// Convert into [0, 1] range if it isn't already.
return ( $n % $max ) / (float) $max;
}