上一篇分析了WPF元素中布局系統的MeasureOverride()和ArrangeOverride()方法,本節將進一步深入分析和研究元素如何渲染它們自身,
大多數WPF元素通過組合方式創建可視化外觀,元素通過其他更基礎的元素進行構建,比如,使用標記定義用戶控制元件的組合元素,處理標記方式與自定義視窗中的XAML相同,使用控制元件模板為自定義控制元件提供可視化樹,并且當創建自定義面板時,根本不必定義任何可視化細節,組合元素由控制元件使用者提供,并添加到Children集合中,
? 接下來就是繪制內容,在WPF中,一些累需要負責繪制內容,在WPF中,這些類位于元素樹的底層,在典型視窗中,是通過單獨的文本、形狀以及位圖執行渲染的,而不是通過高級元素,
OnRender()方法
為了執行自定義渲染,元素必須重寫OnRender()方法,該方法繼承自UIElement基類,一些控制元件使用OnRender()方法繪制可視化細節并使用組合在其上疊加其他元素,Border和Panel類是兩個例子,Border類在OnRender()方法中繪制邊框,Panel類在OnRender()方法中繪制背景,Border和Panel類都支持子內容,并且這些子內容在自定義的繪圖細節之上進行渲染,
OnRender()方法接收一個DrawingCntext物件,該物件為繪制內容提供了一套很有用的方法,在OnRender()方法中執行繪圖的主要區別是不能顯式的創建和關閉DrawingContext物件,這是因為幾個不同的OnRender()方法可能使用相同的DrawingContext物件,例如派生的元素可以執行一些自定義繪圖操作并呼叫基類中的OnRender()方法來繪制其他內容,這種方法是可行的,因為當開始這一程序時,WPF會自動創建DrawingContext物件,并且當不再需要時關閉該物件,
OnRender()方法實際上沒有將內容繪制到螢屏上,而是繪制到DrawingContext物件上,然后WPF快取這些資訊,WPF決定元素何時需要重新繪制并繪制使用DrawingContext物件創建的內容,這是WPF保留模式圖形系統的本質--由開發人員定義內容,WPF無縫的管理繪制和重繪程序,
關于WPF渲染,大多數類是通過其他更簡單的類構建的,并且對于典型的控制元件,為了找到實際重寫OnRender()方法的類,需要進入到控制元件元素樹種非常深的層次,下面是一些重寫了OnRender()方法的類:
- TextBlock類 無論在何處放置文本,都會有TextBlock物件使用使用OnRender()方法繪制文本,
- Image類,Image類重寫OnRender()方法,使用DrawingContext.DrawImage()方法繪制圖形內容,
- MediaElement類,如果正在使用該類播放視頻檔案,該類會重寫OnRender()方法以繪制視頻幀,
- 各種形狀類,Shape基類重寫了OnRender()方法,通過使用DrawingContext.DrawGeometry()方法,繪制在其內部存盤的Geometry物件,根據Shape類的特定派生類,Geometry物件可以表示橢圓、矩形、或更復雜的由直線和曲線構成的路徑,許多元素使用形狀繪制小的可視化細節,
- 各種修飾類,比如ButtonChrome和ListBoxChrome繪制通用控制元件的外側外觀,并在具體指定的內部放置內容,其他許多繼承自Decorator的類,如Border類,都重寫了OnRender()方法,
- 各種面板類,盡管面板的內容是由其子元素提供的,但是OnRender()方法繪制具有背景色(假設設定了Background屬性)的矩形,
重寫OnRender()方法不是渲染內容并且將其添加到用戶界面的唯一方法,也可以創建DrawingVisual物件,并使用AddVisualChild()方法為UIElement物件添加該可視化物件,然后呼叫DrawingVisual.RenderOpen()方法為DrawingVisual物件檢索DrawingContext物件,并使用回傳的DrawingContext物件渲染DrawingVisual物件的內容,
在WPF種,一些元素使用這種策略在其他元素內容之上現實一些圖形細節,例如在拖放指示器、錯誤提示器以及焦點框種可以看到這種情況,在所有這些情況種,DrawingVisual類允許元素在其他內容之上繪制內容,而不是在其他內容之下繪制內容,但對于大部分情況,是在專門的OnRender()方法種進行渲染,
寫了這么多是不是不好理解?多看幾遍,這里我除了比較啰嗦的引跑題的內容,其他的基本上原封不動的抄了過來,或者等看完下面的內容,在回來上面從新讀一遍,上面的內容主要是講應用場景,我自認為我總結的沒有他的好《編程寶典》,就全拿過來了,
請注意,可能看到這里就發現這些東西也不常用,為啥要放到這個入門的系列里,因為在某些場景下,這種OnRender()更適用,因為前段時間熬了半個月的夜,寫一個通過Stylus寫字時字體美化的效果,主要邏輯就是OnRender()這些相關的內容,所以我覺得在客戶端開發中,會遇到這種使用OnRender()能更好更快速解決問題的場景,現在開始本章的學習,
什么場合合適使用較低級的OnRender()方法,
大多數自定義元素不需要自定義渲染,但是當屬性發生變化或執行特定操作時,需要渲染復雜的變化又特別大的可視化外觀,此時使用自定義的渲染方法可能更加簡單并且更便捷,
我們通過一段代碼來演示一個簡單的效果,我們在用戶移動滑鼠時,顯示一個跟隨滑鼠的光圈,
我們創建名為CustomDrawnElement.cs的類,繼承自FrameworkElement類,該類只提供一個可以設定的屬性漸變的背景色(前景色被硬編碼為白色),
使用Propdp=>2次tab創建依賴項屬性BackgroundColor,注意這里的Metadata被修改為FrameworkPropertyMetadata,并且設定了AffectsRender,F12跳轉過去,提示更改此依賴屬性的值會影響呈現或布局組合的某一方面(不是測量或排列程序),因此,無論何時改變了背景色,WPF都會自動呼叫OnRender()方法,當滑鼠移動時,也需要確保呼叫了OnRender()方法,通過在合適的位置使用InvalidateVisual()方法來實作,
public class CustomDrawnElement : FrameworkElement
{
public Color BackgroundColor
{
get { return (Color)GetValue(BackgroundColorProperty); }
set { SetValue(BackgroundColorProperty, value); }
}
// Using a DependencyProperty as the backing store for BackgroundColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register("BackgroundColor", typeof(Color), typeof(CustomDrawnElement), new FrameworkPropertyMetadata(Colors.Yellow, FrameworkPropertyMetadataOptions.AffectsRender));
protected override void onm ouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
this.InvalidateVisual();
}
protected override void onm ouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
this.InvalidateVisual();
}
}
當這些都做完時,剩下就是我們需要重寫的OnRender()方法了,我們通過這個方法繪制元素背景,ActualWidth和ActualHeight屬性指示控制元件最終的渲染尺寸,為了保證能在當前滑鼠正確的位置來渲染,我們需要一個方法來計算當前滑鼠位置和渲染的中心點,
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
Rect bounds = new Rect(0, 0, base.ActualWidth, base.ActualHeight);
drawingContext.DrawRectangle(GetForegroundBrush(), null, bounds);
}
private Brush GetForegroundBrush()
{
if (!IsMouseOver)
{
return new SolidColorBrush(Color.FromRgb(0x7D, 0x7D, 0xFF));
}
else
{
RadialGradientBrush brush = new RadialGradientBrush(Color.FromRgb(0xE0, 0xE0,0xE0), Color.FromRgb(0x7D, 0x7D, 0xFF));
brush.RadiusX = 0.9;
brush.RadiusY = 0.9;
Point absoluteGradientOrigin = Mouse.GetPosition(this);
Point relativeGradientOrigin = new Point(absoluteGradientOrigin.X / base.ActualWidth, absoluteGradientOrigin.Y / base.ActualHeight);
brush.GradientOrigin = relativeGradientOrigin;
brush.Center = relativeGradientOrigin;
return brush;
}
}
在主表單中添加對該元素的使用:
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CustomOnRender"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<local:CustomDrawnElement Width="400" Height="300"/>
<StackPanel Margin="100">
<TextBlock Text="測驗TextBlock" Width="100" />
<Button Width="120" Content="fffff"/>
</StackPanel>
</Grid>
</Window>

但是如果這么實作的話,就會出現一個和之前學習內容矛盾的問題,如果在控制元件中使用自定義繪圖的話,我們硬編碼了繪圖邏輯,控制元件的可視化外觀就不能通過模板進行定制了,
更好的辦法是設計單獨的繪制自定義內容的元素,然后再控制元件的默認模板內部使用自定義元素,
自定義繪圖元素通常扮演兩個角色:
- 它們繪制一些小的圖形細節,(滾動按鈕上的箭頭),
- 它們再另一個元素周圍提供更加詳細的背景或邊框,
我們使用自定義裝飾元素,通過修改上面的例子來完成,我們新建一個CustomDrawnDecorator類繼承自Decorator類;
重新修改代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace CustomOnRender
{
public class CustomDrawnElementDecorator : Decorator
{
public Color BackgroundColor
{
get { return (Color)GetValue(BackgroundColorProperty); }
set { SetValue(BackgroundColorProperty, value); }
}
// Using a DependencyProperty as the backing store for BackgroundColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register("BackgroundColor", typeof(Color), typeof(CustomDrawnElementDecorator), new FrameworkPropertyMetadata(Colors.Yellow, FrameworkPropertyMetadataOptions.AffectsRender));
protected override void onm ouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
this.InvalidateVisual();
}
protected override void onm ouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
this.InvalidateVisual();
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
Rect bounds = new Rect(0, 0, base.ActualWidth, base.ActualHeight);
drawingContext.DrawRectangle(GetForegroundBrush(), null, bounds);
}
private Brush GetForegroundBrush()
{
if (!IsMouseOver)
{
return new SolidColorBrush(Color.FromRgb(0x7D, 0x7D, 0xFF));
}
else
{
RadialGradientBrush brush = new RadialGradientBrush(Color.FromRgb(0xE0, 0xE0, 0xE0), Color.FromRgb(0x7D, 0x7D, 0xFF));
brush.RadiusX = 0.9;
brush.RadiusY = 0.9;
Point absoluteGradientOrigin = Mouse.GetPosition(this);
Point relativeGradientOrigin = new Point(absoluteGradientOrigin.X / base.ActualWidth, absoluteGradientOrigin.Y / base.ActualHeight);
brush.GradientOrigin = relativeGradientOrigin;
brush.Center = relativeGradientOrigin;
return brush;
}
}
protected override Size MeasureOverride(Size constraint)
{
//return base.MeasureOverride(constraint);
UIElement child = this.Child;
if (child != null)
{
child.Measure(constraint);
return child.DesiredSize;
}
else
{
return new Size();
}
}
}
}
<Window x:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CustomOnRender"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ControlTemplate x:Key="WithCustomChrome" >
<local:CustomDrawnElementDecorator BackgroundColor="LightGray">
<ContentPresenter Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
Content="{TemplateBinding ContentControl.Content}" RecognizesAccessKey="True"/>
</local:CustomDrawnElementDecorator>
</ControlTemplate>
</Window.Resources>
<Page Template="{StaticResource WithCustomChrome}">
<StackPanel Margin="100">
<TextBlock Text="測驗TextBlock" Width="100" />
<Button Width="120" Content="fffff"/>
</StackPanel>
</Page>
<!-- <local:CustomDrawnElement Width="400" Height="300"/>-->
</Window>

這篇主要內容就是如何使用OnRender()方法進行重繪,目前就這么多拉,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/285415.html
標籤:WPF
下一篇:WPF -- 應用啟動慢問題
