赵星汉同学的技术博客 Software testing & software engineering

C#的可视化图层学习笔记

2021-09-13
User


如何使用WPF和C#的可视化图层

C#中,抽象的System.Windows.Media.Visual类型提供了用于呈现图像的部分服务,由于Visual是基类,因此我们需要使用它的派生类来执行实际的操作,主要有DrawingVisual, Viewport3DVisual,ContainerVisual。

使用DrawingVisual类在平面上呈现数据,需要执行以下基本步骤。

  1. 在DrawingVisual中获取DrawingContext对象
  2. 使用DrawingContext呈现图形数据

这是两个最基本的步骤。如果需要呈现的数据响应命中测试计算,需要再执行额外的步骤:

  1. 更新你所呈现的容器中的逻辑树和可视化树
  2. 重写FrameElement类中的两个虚方法,容许容器获取你创建的可视化数据。

基本步骤主要涉及代码如下:

<Window x:Class="Wpftest.MainWindow"
        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:Wpftest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel Background="AliceBlue" Name="myStackPanel">
        <Image Name="myImage"  Height="50" Loaded="MyImage_Loaded" Margin="100,100,0,0"/>
    </StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Wpftest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MyImage_Loaded(object sender, RoutedEventArgs e)
        {
            const int TextFontSize = 30;

            //创建一个System.windows.Media.FormattedText对象
            FormattedText text = new FormattedText("Hello Visual Layer",
                new System.Globalization.CultureInfo("en_us"),
                FlowDirection.LeftToRight,
                new Typeface(this.FontFamily, FontStyles.Italic, FontWeights.DemiBold, FontStretches.UltraCondensed),
                TextFontSize,
                Brushes.Green);

            //创建一个DrawingVisual,并获取DrawingContext
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                drawingContext.DrawRoundedRectangle(Brushes.Yellow,new Pen(Brushes.Black,5),
                new Rect(5,5,450,100),20,20);

                drawingContext.DrawText(text, new Point(20, 20));

            }

            //使用DrawingVisual中的数据创建位图
            RenderTargetBitmap bmp = new RenderTargetBitmap(500, 200, 100, 90, PixelFormats.Pbgra32);
            bmp.Render(drawingVisual);

            myImage.Source = bmp;
        }
    }
}

Comments

Content