[UWP]通過自定義XamlCompositionBrushBase實現圖片平鋪

来源:https://www.cnblogs.com/dino623/archive/2019/11/20/using_XamlCompositionBrushBase_to_implement_the_tiling_function_of_image.html
-Advertisement-
Play Games

1. 什麼是XamlCompositionBrushBase 我早就想試試自定義XamlCompositionBrushBase,但一直沒機會。上一篇文章介紹到 "使用Win2D的BorderEffect實現圖片的平鋪功能" ,原理很簡單,但每次都要寫這些代碼很繁瑣,正好就用這個作為例子試試Xaml ...


1. 什麼是XamlCompositionBrushBase

我早就想試試自定義XamlCompositionBrushBase,但一直沒機會。上一篇文章介紹到使用Win2D的BorderEffect實現圖片的平鋪功能,原理很簡單,但每次都要寫這些代碼很繁瑣,正好就用這個作為例子試試XamlCompositionBrushBase。

CompositionBrush靈活多變,它的基本用法如下:

  1. 通過Compositor創建CompositionBrush;
  2. 配置CompositionBrush;
  3. 創建SpriteVisual並將它的Brush設置為CompositionBrush;
  4. 使用ElementCompositionPreview.SetElementChildVisual 將SpriteVisual設置到某個UIElement的可視化層里。

這些步驟很繁瑣,而且不能用在XAML中。XamlCompositionBrushBase提供了將CompositionBrush用在XAML中一個橋梁,他繼承自Brush類,可以直接像普通的XAML 畫筆(如SolidColorBrush)那樣直接用在XAML中。

如上圖所示,Windows Community Toolkit中已經提了很不少XamlCompositionBrushBase的實現,它們的使用方式已經有很多文章介紹,這裡不一一列舉。

2. 自定義XamlCompositionBrushBase

這篇文章將介紹一個自定義的畫筆:TiledImageBrush,它的主要目標是實現ImageBrush沒有的圖片平鋪功能,並且它可以在XAML中使用,使用方式如下:

<Rectangle IsHitTestVisible="False">
    <Rectangle.Fill>
        <controls:TiledImageBrush Source="ms-appx:///Assets/flutter.png"/>
    </Rectangle.Fill>
</Rectangle>

順便複習下普通的ImageBrush的用法:

<Rectangle >
    <Rectangle.Fill>
        <ImageBrush ImageSource="ms-appx:///Assets/flutter.png"/>
    </Rectangle.Fill>
</Rectangle>

看起來TiledImageBrush的用法是不是和ImageBrush很像?接下來講解TiledImageBrush的實現步驟。TiledImageBrush繼承自XamlCompositionBrushBase,而實現XamlCompositionBrushBase的一般步驟如下:

protected override void OnConnected()
{
    // Delay creating composition resources until they're required.
    if (CompositionBrush == null)
    {
         CompositionBrush = CreateCompositionBrush();//Create A CompositionBrush.
    }
}

protected override void OnDisconnected()
{
    // Dispose of composition resources when no longer in use.
    if (CompositionBrush != null)
    {
        CompositionBrush.Dispose();
        CompositionBrush = null;
    }
}

首先重寫OnConnected,當畫筆在屏幕上首次用於繪製元素時會調用這個函數。在這個函數里創建CompositionBrush並賦值給XamlCompositionBrushBase.CompositionBrush

然後重寫OnDisconnected,它在畫筆不再用於繪製任何元素時被調用。在這個函數里儘可能地釋放各種資源,例如CompositionBrush。這兩步就是實現XamlCompositionBrushBase的基本步驟。

創建CompositionBrush有很多種玩法,我之前寫過兩篇文章分別介紹 CompositionBrush入門在CompositionBrush上使用Effect。這裡使用使用Win2D的BorderEffect實現圖片的平鋪功能這篇文章里介紹到的代碼,首先使用LoadedImageSurface.StartLoadFromUri創建CompositionSurfaceBrush,然後加入到BorderEffect里實現圖片平鋪,然後把產生的CompositionEffectBrush賦值給XamlCompositionBrushBase.CompositionBrush

TiledImageBrush中添加了Source屬性用於設置圖片Uri(實際上是個ImageSource類型),模仿ImageBrush,這裡的Source也是一個ImageSource類型的屬性,雖然實際上使用的是它的UriSource。詳細代碼如下:

public ImageSource Source
{
    get => (ImageSource)GetValue(SourceProperty);
    set => SetValue(SourceProperty, value);
}

private void UpdateSurface()
{
    if (Source != null && _surfaceBrush != null)
    {
        var uri = (Source as BitmapImage)?.UriSource ?? new Uri("ms-appx:///");
        _surface = LoadedImageSurface.StartLoadFromUri(uri);
        _surfaceBrush.Surface = _surface;
    }
}

OnConnected的詳細代碼如下:

protected override void OnConnected()
{
    base.OnConnected();

    if (CompositionBrush == null)
    {
        _surfaceBrush = Compositor.CreateSurfaceBrush();
        _surfaceBrush.Stretch = CompositionStretch.None;

        UpdateSurface();

        _borderEffect = new BorderEffect()
        {
            Source = new CompositionEffectSourceParameter("source"),
            ExtendX = Microsoft.Graphics.Canvas.CanvasEdgeBehavior.Wrap,
            ExtendY = Microsoft.Graphics.Canvas.CanvasEdgeBehavior.Wrap
        };

        _borderEffectFactory = Compositor.CreateEffectFactory(_borderEffect);
        _borderEffectBrush = _borderEffectFactory.CreateBrush();
        _borderEffectBrush.SetSourceParameter("source", _surfaceBrush);
        CompositionBrush = _borderEffectBrush;
    }
}

這樣一個基本的XamlCompositionBrush就完成了,完整的代碼可以在這裡查看:

OnePomodoro_TiledImageBrush.cs at master

3. 參考

XamlCompositionBrushBase Class (Windows.UI.Xaml.Media) - Windows UWP applications _ Microsoft Docs

WindowsCommunityToolkit_Microsoft.Toolkit.Uwp.UI.Media_Brushes at master

UWP TiledBrush - CodeProject

Working with Brushes and Content – XAML and Visual Layer Interop, Part One - Windows Developer Blog
)


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's ...
  • PUB(Publisher)文件格式用於新聞稿,小冊子和海報之類的專業設計。它們還可以用於集成和存儲數據源以進行郵件合併和生成數據表。 Aspose一直致力於研究用於執行文件間格式轉換,對文件進行操作(例如創建、版本、操作等)的文件格式API。好消息來啦!專門解決.pub格式載入和轉換為PDF的AP ...
  • 1.下載 .Net Core Runtime 和 Hosting Bundle 下載地址:https://dotnet.microsoft.com/download/dotnet-core 分別下載 Runtime for Windows x64(x86) 和 Hosting Bundle,並安裝。 ...
  • Microsoft Office是市場上最強大的繪圖工具之一。通常,執行基本任務會較為困難 - 比如在頁面內繪製形狀等等。 如果你想以編程方式使用它並開發Add-Ons,小編為你推薦Aspose.Diagram。 Aspose.Diagram for .NET是專門用於處理Microsoft Vis ...
  • using MailKit.Net.Smtp;using MimeKit;using System;using System.Collections.Generic;using System.IO;using System.Threading.Tasks; namespace ConsoleApp2 ...
  • NuGet 是 .NET 平臺下的一個免費、開源的包管理開發工具。 修改全局包管理目錄 通過 NuGet 安裝包時,NuGet 先將包下載至一個統一的目錄,預設路徑是: 下載的包多了以後,會導致 C 盤空間被大量占用。我們可以通過修改配置將其指定到自定義的目錄下。 搜索 文件,預設位置是: ,在根節 ...
  • 一、前言 最近有在看 DDD 的相關資料以及微軟的 eShopOnContainers 這個項目中基於 DDD 的架構設計,在 Ordering 這個示例服務中,可以看到各層之間的代碼調用與我們之前傳統的調用方式似乎差異很大,整個項目各個層之間的代碼全部是通過註入 IMediator 進行調用的,F ...
  • 1 IWorkbook workbook = new XSSFWorkbook(); 2 ISheet sheet = workbook.CreateSheet("-"); 3 IRow row = sheet.CreateRow(0);//標題 4 5 IRow titleRow = row.Cr... ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...