主頁 > .NET開發 > WPF教程十四:了解元素的渲染OnRender()如何使用

WPF教程十四:了解元素的渲染OnRender()如何使用

2021-06-09 15:00:37 .NET開發

上一篇分析了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實作Android(3D)選單翻轉影片

下一篇:WPF -- 應用啟動慢問題

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more