Files
ShrlAlgoToolkit/Melskin/Converters/Internal/AlphaToPercentConverter.cs
2026-02-17 22:17:13 +08:00

44 lines
1.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.Windows.Data;
namespace Melskin.Converters.Internal;
/// <summary>
/// 该类实现了IValueConverter接口用于将Alpha透明度值0-255与百分比字符串0%-100%)之间进行转换。
/// 在Convert方法中接受一个0到255之间的整数值作为输入并将其转换为相应的百分比字符串表示形式。
/// 而在ConvertBack方法中则执行相反的操作接收一个百分比字符串并尝试将其解析回0至255范围内的整数。
/// 若输入非预期格式或超出合理范围时,转换器将采取适当措施以确保输出结果的有效性。
/// </summary>
internal class AlphaToPercentConverter : IValueConverter
{
public static readonly AlphaToPercentConverter Instance = new();
/// <inheritdoc />
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is byte alpha)
{
// 将 0-255 的值转换为 0-100 的百分比字符串
return $"{Math.Round(alpha / 255.0 * 100.0)}%";
}
return "100%";
}
/// <inheritdoc />
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is string percentStr)
{
// 移除 '%' 符号并尝试解析
if (double.TryParse(percentStr.TrimEnd('%'), out var percent))
{
var clampedPercent = Math.Max(0, Math.Min(100, percent));
var alpha = (byte)Math.Round(clampedPercent / 100.0 * 255.0);
return alpha;
}
}
// 如果转换失败,返回 UnsetValue 以保留原值
return DependencyProperty.UnsetValue;
}
}