【问题标题】:How to overlay a color onto a Canvas and also add an exlusion region in WPF如何在画布上叠加颜色并在 WPF 中添加排除区域
【发布时间】:2011-07-04 16:05:18
【问题描述】:

所以,一个简单的问题,我相信你更有经验的 WPF 人,但我有一个简单的任务(在 WinForms 中),我在 WPF 中实现有点麻烦。当我在 WPF 中遇到这样的事情时,通常只是意味着有一个我不知道的功能,但我找不到任何示例。问题来了:

想象一个显示图像的画布。在这张图片上,我有一个可以由用户操作的可调整大小的矩形。我希望这个矩形之外的所有区域都用半透明颜色遮盖。在 WinForms 中,我会简单地覆盖 OnPaint,向我的 Graphics 对象添加一个排除区域,然后用我的半透明颜色填充 Graphics 对象。

所以,我的第一个想法是为我的 Canvas 覆盖 OnRender,并使用 DrawingContext 以同样的方式执行此操作。所以,我尝试了这个作为测试:

protected override void OnRender( DrawingContext dc )
{
    base.OnRender( dc );
    var clipRect = new Rect( 128, 128, 1024, 462 );
    dc.PushClip( new RectangleGeometry( clipRect ) );
    var bounds = new Rect( 0, 0, this.ActualHeight, this.ActualWidth );
    dc.DrawRectangle( new SolidColorBrush( Colors.White.ApplyAlpha( 128 ) ), null, bounds );
}

没有骰子; OnRender 从不真正触发。

根据我使用 WPF 的经验(实际上是大多数事情),我意识到,当看起来应该很简单的事情实际上很困难时,我做错了。那么,关于如何使用剪辑区域设置蒙版颜色的任何建议?提前致谢。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您可以使用带有排除区域的 opacitymask,如下所示:

    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Canvastest"
        x:Class="Canvastest.MainWindow"
        x:Name="Window"
        Title="MainWindow"
        Width="640" Height="480">
    
        <Grid x:Name="LayoutRoot">
            <Canvas Margin="8">
                <Image x:Name="image" Height="410" Width="592" Source="Koala.jpg" Stretch="UniformToFill"/>
                <Rectangle Fill="#FD9D5C5C" Width="{Binding ActualWidth, ElementName=image}" Height="{Binding ActualHeight, ElementName=image}" Name="rect">
                    <Rectangle.OpacityMask>
                        <DrawingBrush Stretch="None">
                            <DrawingBrush.Drawing>                                                      
                                <GeometryDrawing Brush="#99ffffff">
                                    <GeometryDrawing.Geometry>
                                        <CombinedGeometry GeometryCombineMode="Exclude">
                                            <CombinedGeometry.Geometry1>
                                                <RectangleGeometry>
                                                    <RectangleGeometry.Rect>
                                                        <MultiBinding Converter="{local:RectConverter}">
                                                            <Binding Path="(Canvas.Left)" ElementName="image"/>
                                                            <Binding Path="(Canvas.Top)" ElementName="image"/>
                                                            <Binding Path="Width" ElementName="rect"/>
                                                            <Binding Path="Height" ElementName="rect"/>
                                                        </MultiBinding>
                                                    </RectangleGeometry.Rect>
                                                </RectangleGeometry>
                                            </CombinedGeometry.Geometry1>
                                            <CombinedGeometry.Geometry2>
                                                <RectangleGeometry>
                                                    <RectangleGeometry.Rect>
                                                        <MultiBinding Converter="{local:RectConverter}">
                                                            <Binding Path="(Canvas.Left)" ElementName="thumb"/>
                                                            <Binding Path="(Canvas.Top)" ElementName="thumb"/>
                                                            <Binding Path="Width" ElementName="thumb"/>
                                                            <Binding Path="Height" ElementName="thumb"/>
                                                        </MultiBinding>
                                                    </RectangleGeometry.Rect>
                                                </RectangleGeometry>
                                            </CombinedGeometry.Geometry2>                                       
                                        </CombinedGeometry>                                 
                                    </GeometryDrawing.Geometry>                             
                                </GeometryDrawing>
                            </DrawingBrush.Drawing>
                        </DrawingBrush>
                    </Rectangle.OpacityMask>
                </Rectangle>
                <Thumb Name="thumb" DragDelta="Thumb_DragDelta" Width="50" Height="50" Background="Transparent" Cursor="SizeAll" Canvas.Left="50" Canvas.Top="50">
                    <Thumb.Style>
                        <Style TargetType="Thumb">
                            <Setter Property="OverridesDefaultStyle" Value="True"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="Thumb">
                                        <Grid Background="Transparent">
    
                                        </Grid>                                    
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Thumb.Style>
                </Thumb>
                <Grid Width="{Binding Width, ElementName=thumb}" Height="{Binding Height, ElementName=thumb}" Canvas.Left="{Binding (Canvas.Left), ElementName=thumb}" Canvas.Top="{Binding (Canvas.Top), ElementName=thumb}">
                    <Thumb Width="5" Height="5" Cursor="SizeNWSE" DragDelta="Thumb_DragDelta_1" Background="Transparent" Margin="0,0,-5,-5" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                </Grid>
    
            </Canvas>
        </Grid>
    </Window>
    

    使用代码隐藏:

    public partial class MainWindow : Window
        {
            public MainWindow()
            {
                this.InitializeComponent();
    
            }
    
            private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
            {
                var thumb = sender as Thumb;
                var left = (double)thumb.GetValue(Canvas.LeftProperty);
                var top = (double)thumb.GetValue(Canvas.TopProperty);
    
                if (double.IsNaN(left))
                    left = 0.0;
                if (double.IsNaN(top))
                    top = 0.0;
                left += e.HorizontalChange;
                top += e.VerticalChange;
                thumb.SetValue(Canvas.LeftProperty,left);
                thumb.SetValue(Canvas.TopProperty, top);
            }
    
            private void Thumb_DragDelta_1(object sender, DragDeltaEventArgs e)
            {            
                thumb.Width += e.HorizontalChange;
                thumb.Height += e.VerticalChange;
            }
        }
    
        public class RectConverter : MarkupExtension,IMultiValueConverter
        {
            public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
            {
                if (values == null || values.Length != 4 || values.OfType<double>().Count() != 4) return new Rect(0, 0, 0, 0);
                for (var i = 0; i < values.Length; i++)
                    if (double.IsNaN((double)values[i]))
                        values[i] = 0.0;
                return new Rect((double)values[0], (double)values[1], (double)values[2], (double)values[3]);
            }
    
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
    
            public override object ProvideValue(IServiceProvider serviceProvider)
            {
                return new RectConverter();
            }
        }
    

    编辑:用这个来编写一个完整的例子更有趣

    【讨论】:

    • 嘿,非常感谢您提供如此完整的示例。我在让 rect 出现时遇到了一些麻烦,但这可能是我做错了。我将在一个干净的测试项目中尝试它以删除一些变量,但如果它有效,我会将其标记为已接受。再次感谢!
    • 显然这是一项在 WinForms 中要容易得多的任务 =D
    • @Ed 你真的这么认为吗?我对 Winforms 中的控件了解不多,但我认为在 WPF 中使用 Thumb 元素(就像我所做的那样 - 或者最好更简洁一些)比在 Winforms 中处理用户输入要容易得多
    • 哦,是的,用户输入要容易得多,正是这个特殊问题在 WPF 中更复杂(在 WinForms 中只有 2 行代码)。就像我说的,我可能只是错过了一些简单的东西。今晚晚些时候我会有时间玩弄它。
    猜你喜欢
    • 1970-01-01
    • 2020-05-07
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    相关资源
    最近更新 更多