WPF Getting started with Direct2d1 drawing

Source: Internet
Author: User
Tags creative commons attribution dot net dot net framework

This article tells you how to use d2d paint in WPF.

This article is a series

    • WPF Getting started with Direct2d1 drawing

    • WPF draws basic graphics using DIRECT2D1 paint

    • WPF uses SHARPDX

    • WPF uses SHARPDX to display in D3dimage

    • WPF uses encapsulated SHARPDX controls

    • WPF uses SHARPDX asynchronous rendering

What is D2D

In fact, many small partners are now looking at this blog for rendering performance just to hear DirectX. I saw a few blogs about this in the blog park. Even if there is very little to say how to use WPF.

So D2D is a high-performance approach, specifically how to do? Based on the Direct3D, hardware-accelerated functionality can be used, even in the absence of video cards, the performance of soft rendering is faster than GDI, but rendering static or recommended to use GDI.

The rendering now used by the WPF bottom layer is Dx9 rendering or using Dx11 Dx12 to optimize FL9 rendering, so the performance is virtually the same as the direct use of d2d, but WPF does not fully use DX, so if you write your own performance will be relatively high.

Because WPF rendering uses Dx9 or although Dx11 Dx12 is used, the optimization is FL9, so many devices are now unable to use the full performance.

DIRECT2D Operational Requirements

This is what I see from the Great God blog, if you need to run direct2d then you need to be Win7. So now it can be run almost directly, and few people will use devices below Win7.

Installation

Here is my installation from Nuget, this is very old library, not very recommended for everyone to use.

Nuget Search Windowsapicodepackdirectx can be installed, if you do not know which one to install, click Windowsapicodepackdirectx

This library is just a x64 library, so you need to set up the environment to run it.

Environment

If the direct use of this library is unable to run, the following code is just as quick for everyone to get started and cannot be used for the product. Installing this library can be used in the x64 process, but not in the x86 process.

And this library does not run directly in the DOT NET Framework 4.5 environment, you need to create an app. config file to add the following code. Note that you should modify the creation of the project using the DOT NET Framework 4.5 instead of the higher version.

<?xml version="1.0" encoding="utf-8" ?><configuration>  <startup useLegacyV2RuntimeActivationPolicy="true">    <supportedRuntime version="v4.0" sku = ".NETFramework,Version=v4.5"/>    <supportedRuntime version="v2.0.50727"/>  </startup></configuration>

So how do you get the software to use the x64 process? Try right click on the project click Properties, on the build page can see the platform target, select x64 will compile x64 software.

If you are interested in a platform target, see what is the difference between WPF compilation for AnyCPU and x86

Create a factory

First open the MainPage code, add the following code

using D2D = Microsoft.WindowsAPICodePack.DirectX.Direct2D1;

So there is no need to write so much code, because all Microsoft.WindowsAPICodePack.DirectX.Direct2D1 the use can be used D2D to find, so that the following code can be directly copied to run.

The first step in using DIRECT2D1 is to create a factory.

Although the factory has a lot of heavy loads, but here will not tell you, because just quick to get started, if you need to know the meaning of the parameters, please read more articles.

       public MainWindow()        {            InitializeComponent();            Loaded += (s, e) =>            {                var d2DFactory = D2D.D2DFactory.CreateFactory(D2D.D2DFactoryType.Multithreaded);            };        }

Write the code in Loaded because you need to get the window below.

Get window

From the above code, you might say why you need to write in load, because you need to get the window and take it after load is not empty. Window creation Although not only in Loaded to take, but for the code is relatively simple, so write in Loaded, then get General is can use.

Use the following code to get to the window

                var windowHandle = new WindowInteropHelper(this).Handle;
Render target

The most important thing is to create rendertarget, use the following code

var renderTarget = d2DFactory.CreateHwndRenderTarget(new D2D.RenderTargetProperties(),                    new D2D.HwndRenderTargetProperties(windowHandle,                        new D2D.SizeU((uint) ActualWidth, (uint) ActualHeight),                        D2D.PresentOptions.RetainContents));

In fact, the above code can not be used in the actual project, because the size of the write, if the window modified size, then the display is generally not expected.

You also need to use rendertarget when rendering, create a field to save

    public MainWindow()        {            InitializeComponent();            Loaded += (s, e) =>            {                var d2DFactory = D2D.D2DFactory.CreateFactory(D2D.D2DFactoryType.Multithreaded);                var windowHandle = new WindowInteropHelper(this).Handle;                var renderTarget = d2DFactory.CreateHwndRenderTarget(new D2D.RenderTargetProperties(),                    new D2D.HwndRenderTargetProperties(windowHandle,                        new D2D.SizeU((uint) ActualWidth, (uint) ActualHeight),                        D2D.PresentOptions.RetainContents));                _renderTarget = renderTarget;            };        }        private D2D.RenderTarget _renderTarget;
Write line Segments

Said above is mainly take rendertarget, because get rendertarget and get drawcontext like, oneself try to point RenderTarget can see a lot of drawing method, inside the performance is high.

Then try writing a segment to the RenderTarget

Because you need to know when to render, add the following code first. Getting a rendering at CompositionTarget is a performance-consuming process, but in order for DX rendering to be the same as WPF time, this event needs to be rendered. Do not allow this method to execute for a long time, in addition to drawing out do not do anything else.

            CompositionTarget.Rendering += OnRendering;

To draw a line, you need to know the two points of the line, and the color and width of the line. However, the style of incoming lines in RenderTarget requires the following method. Note that the value passed in is ColorF and the three values are [0,1], so passing in the normal color needs to be calculated.

How to create a brush

            var brush = _renderTarget.CreateSolidColorBrush(new D2D.ColorF(0, 1, 0));

for rendering

            if (_renderTarget == null)            {                return;            }            _renderTarget.BeginDraw();            var brush = _renderTarget.CreateSolidColorBrush(new D2D.ColorF(0, 1, 0));            _renderTarget.DrawLine(new D2D.Point2F(10, 10), new D2D.Point2F(100, 100), brush, 10);                        _renderTarget.EndDraw();

The rendering needs to be BeginDraw and then drawn, and finally called EndDraw drawn. Note that if the run does not see the draw, then please first see if it is tuned several times BeginDraw no match EndDraw.

You can see the following interface when you try to run

Then look at the CPU, almost no need.

Here is a small change, write a moving diagram, the following code is put in the last.

DIRECT2D Tutorial i--Introduction and the first example-Vancan-a Millet-blog Park

All code: WPF direct2d Getting Started-csdn download

       Public MainWindow () {InitializeComponent ();            Compositiontarget.rendering + = onrendering; Loaded + = (s, e) = = {var d2dfactory = d2d. D2dfactory.createfactory (d2d.                d2dfactorytype.multithreaded); var windowhandle = new Windowinterophelper (this).                Handle; var rendertarget = d2dfactory.createhwndrendertarget (new d2d. Rendertargetproperties (), New d2d. Hwndrendertargetproperties (WindowHandle, New d2d. Sizeu (UINT) actualwidth, (UINT) ActualHeight), d2d.                presentoptions.retaincontents)); _redbrush = Rendertarget.createsolidcolorbrush (new d2d.                ColorF (1, 0, 0, 1)); _greenbrush = Rendertarget.createsolidcolorbrush (new d2d.                ColorF (0, 1, 0, 1)); _bluebrush = Rendertarget.createsolidcolorbrush (new d2d.                ColorF (0, 0, 1, 1));            _rendertarget = RenderTarget;        };        }Private D2D.        RenderTarget _rendertarget; Private D2D.        SolidColorBrush _redbrush; Private D2D.        SolidColorBrush _greenbrush; Private D2D.        SolidColorBrush _bluebrush;                private void Onrendering (object sender, EventArgs e) {if (_rendertarget = = null) {            Return } d2d.            SolidColorBrush brush = null; Switch (ran.                    Next (3)) {case 0:brush = _redbrush;                Break                    Case 1:brush = _greenbrush;                Break                    Case 2:brush = _bluebrush;            Break            } _rendertarget.begindraw (); _rendertarget.drawrectangle (New d2d.            RECTF (_x, _y, _x + ten, _y +), brush, 1);            _rendertarget.enddraw ();            _x = _x + _dx;            _y = _y + _dy;          if (_x >= ActualWidth-100 | | _x <= 0) {      _DX =-_DX;            } if (_y >= ActualHeight-100 | | _y <= 0) {_dy =-_dy;        }} private float _dx = 1;        private float _dy = 1;        private float _x;        private float _y; Private random ran = new random ();
More Blogs

Why use Directcomposition

Direct2D of C + + see DIRECT2D

I set up my own blog https://lindexi.gitee.io/welcome everyone to visit, there are many new blog. Only when I see the blog is mature will not be placed in the CSDN or blog park, but once published, no longer update

If you see anything in the blog do not understand, welcome to communicate, I set up the Dotnet Vocational Technical College welcome everyone to join


This work is licensed under the Creative Commons Attribution-NonCommercial use-Share 4.0 International license agreement in the same way. Welcome to reprint, use, republish, but be sure to keep the article Attribution Lindesi (including Link: http://blog.csdn.net/lindexi_gd), not for commercial purposes, based on the modified works of this article must be issued with the same license. If you have any questions, please contact me.

WPF Getting started with Direct2d1 drawing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.