WPF 改变亮度

扫码查看

好吧,我有一个黑白应用程序,我需要一个功能来降低亮度,我该怎么做?所有白色都来自保存在 ResourceDictionary(Application.xaml) 中的 SolidColorBrush,我当前的解决方案是放置一个空窗口,该窗口的不透明度为 80%,但这不允许我使用底层窗口。

最佳答案

如果您所有的 UI 元素都使用相同的 Brush ,为什么不直接修改 Brush 以降低亮度?例如:

public void ReduceBrightness()
{
    var brush = Application.Resources("Brush") as SolidColorBrush;
    var color = brush.Color;
    color.R -= 10;
    color.G -= 10;
    color.B -= 10;
    brush.Color = color;
}

在您对 Brush 被卡住的评论后进行编辑:

如果您正在使用其中一种内置画笔(通过 Brushes 类),那么它将被卡住。不要使用其中之一,而是声明您自己的 Brush 而不卡住它:
<SolidColorBrush x:Key="Brush">White</SolidColorBrush>

根据 Robert 对应用程序级资源的评论进行编辑:

罗伯特是对的。在 Application 级别添加的资源如果可卡住,将自动卡住。即使您明确要求不要卡住它们:
<SolidColorBrush x:Key="ForegroundBrush" PresentationOptions:Freeze="False" Color="#000000"/>

我可以看到有两种方法可以解决这个问题:
  • 正如罗伯特所建议的,将资源放在资源树中的较低级别。例如,在 WindowResources 集合中。这使得分享变得更加困难。
  • 将资源放入不可卡住的包装器中。

  • 作为#2 的示例,请考虑以下内容。

    应用程序.xaml:
    <Application.Resources>
        <FrameworkElement x:Key="ForegroundBrushContainer">
            <FrameworkElement.Tag>
                <SolidColorBrush PresentationOptions:Freeze="False" Color="#000000"/>
            </FrameworkElement.Tag>
        </FrameworkElement>
    </Application.Resources>
    

    Window1.xaml:
    <StackPanel>
        <Label Foreground="{Binding Tag, Source={StaticResource ForegroundBrushContainer}}">Here is some text in the foreground color.</Label>
        <Button x:Name="_button">Dim</Button>
    </StackPanel>
    

    Window1.xaml.cs:
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            _button.Click += _button_Click;
        }
    
        private void _button_Click(object sender, RoutedEventArgs e)
        {
            var brush = (FindResource("ForegroundBrushContainer") as FrameworkElement).Tag as SolidColorBrush;
            var color = brush.Color;
            color.R -= 10;
            color.G -= 10;
            color.B -= 10;
            brush.Color = color;
        }
    }
    

    它不是那么漂亮,但它是我现在能想到的最好的。

    关于WPF 改变亮度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/653868/

    10-11 23:05
    查看更多