如果要使用OnRender(DrawingContext drawingContext)
,必须Transparent
在Window
对象中设置背景并覆盖该OnRender
方法。
public MainWindow()
{
InitializeComponent();
//--workaround: set the background as transparent.
Background = Brushes.Transparent;
}
然后覆盖OnRender
方法。代码假定定义:_rectBrush、_rectPen、_rect
protected override void OnRender(DrawingContext drawingContext)
{
//--set background in white
Rect bgRect = new Rect(0, 0, ActualWidth, ActualHeight);
drawingContext.DrawRectangle(Brushes.White, null, bgRect);
//--draw the rectangle
drawingContext.DrawRectangle(_rectBrush, _rectPen, _rect);
}
我希望它有所帮助。
编辑:包括一个例子:
XAML部分:
<Window x:Class="WpfDrawing.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Rectangle Painting" Height="350" Width="525"
MouseLeftButtonDown="MainWindow_OnMouseLeftButtonDown"
MouseLeftButtonUp="MainWindow_OnMouseLeftButtonUp"
MouseMove="MainWindow_OnMouseMove"
Background="Transparent">
</Window>
以及背后的代码:
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace WpfDrawing
{
public partial class MainWindow : Window
{
private Point _p1;
private Point _p2;
private bool _painting;
private readonly Pen _rectPen = new Pen(Brushes.Blue, 1);
private readonly SolidColorBrush _rectBrush = new SolidColorBrush
{
Color = Colors.SkyBlue
};
public MainWindow()
{
InitializeComponent();
//--workaround: set the background as transparent.
Background = Brushes.Transparent;
//--Freeze the painting objects to increase performance.
_rectPen.Freeze();
_rectBrush.Freeze();
}
protected override void OnRender(DrawingContext drawingContext)
{
var rect = new Rect(_p1, _p2);
Debug.WriteLine("OnRender -> " + rect);
//--set background in white
Rect backRect = new Rect(0, 0, ActualWidth, ActualHeight);
drawingContext.DrawRectangle(Brushes.White, null, backRect);
//--draw the rectangle
drawingContext.DrawRectangle(_rectBrush, _rectPen, rect);
}
private void MainWindow_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var p = e.GetPosition(this);
Debug.WriteLine("MainWindow_OnMouseLeftButtonDown -> " + p);
_p1 = _p2 = p;
_painting = true;
InvalidateVisual();
}
private void MainWindow_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
_painting = false;
Debug.WriteLine("MainWindow_OnMouseLeftButtonUp");
}
private void MainWindow_OnMouseMove(object sender, MouseEventArgs e)
{
if (!_painting)
return;
var p = e.GetPosition(this);
Debug.WriteLine("MainWindow_OnMouseMove -> " + p);
_p2 = p;
InvalidateVisual();
}
}
}