Code Monkey home page Code Monkey logo

d2dlib's Introduction

GitHub Nuget

d2dlib

A .NET library for hardware-accelerated, high performance, immediate mode rendering via Direct2D.

By using the graphics context to draw anything on windows form, control or draw in memory via Direct2D. The graphics interface is designed like the normal Windows Form graphics interface, it's easy-to-learn and user-friendly.

Project Language Description Output DLL
d2dlib VC++ Wrapper host-side library, calling Windows SDK and Direct2D API d2dlib.dll
d2dlibexport C# Wrapper client-side library, export the interface provided from d2dlib d2dlibexport.dll
d2dwinform C# Provides the D2DWinForm and D2DControl classes that use Direct2D hardware-acceleration graphics context during rendering d2dwinform.dll

Installation

Get binary from NuGet

install-package unvell.d2dlib

Or install for x64 platform:

install-package unvell.d2dlib-x64

Notes

The Direct2D API is a platform-associated API that requires the application to be targeted to either x86 or x64 platform. To run the application uses this library correctly, the Platform target of the project settings must be set to x86 or x64.

Install manually

Learn how to install manually

Getting Started

  1. Make windows form or control inherited from D2DForm or D2DControl class
  2. Override OnRender(D2DGraphics g) method (do not override .NET OnPaint method)
  3. Draw anything inside OnRender method via the g context

Drawing

Draw rectangle

protected override void OnRender(D2DGraphics g)
{
  var rect = new D2DRect(0, 0, 10, 10);
  g.DrawRectangle(rect, D2DColor.Red);
}

Draw ellipse

var ellipse = new D2DEllipse(0, 0, 10, 10);
g.DrawEllipse(ellipse, D2DColor.Gray);

Draw text

g.DrawText("Hello World", D2DColor.Yellow, this.Font, 100, 200);

Using brush object

Solid color brush

var brush = Device.CreateSolidColorBrush(new D2DColor(1, 0, 0.5));
g.DrawEllipse(rect, brush);

Linear and radio gradient brush

var brush = Device.CreateLinearGradientBrush(new D2DPoint(0, 0), new D2DPoint(200, 100),
  new D2DGradientStop[] {
    new D2DGradientStop(0, D2DColor.White),
    new D2DGradientStop(0.5, D2DColor.Green),
    new D2DGradientStop(1, D2DColor.Black),
  });

Draw bitmap

g.DrawBitmap(bmp, this.ClientRectangle);

Convert GDI+ bitmap to Direct2D bitmap for getting high-performance rendering

// convert to Direct2D bitmap
var d2dbmp = Device.CreateBitmapFromGDIBitmap(gdiBitmap);

// draw Direct2D bitmap
g.DrawBitmap(d2dbmp, this.ClientRectangle);

Drawing on GDI+ bitmap

// create and draw on GDI+ bitmap
var gdiBmp = new Bitmap(1024, 1024);
using (Graphics g = Graphics.FromImage(gdiBmp))
{
  g.DrawString("This is GDI+ bitmap layer", new Font(this.Font.FontFamily, 48), Brushes.Black, 10, 10);
}

// draw memory bitmap on screen
g.DrawBitmap(gdiBmp, this.ClientRectangle);

Learn more about Bitmap. See Example code

Drawing on Direct2D memory bitmap

var bmpGraphics = this.Device.CreateBitmapGraphics(1024, 1024);
bmpGraphics.BeginRender();
bmpGraphics.FillRectangle(170, 790, 670, 80, new D2DColor(0.4f, D2DColor.Black));
bmpGraphics.DrawText("This is Direct2D device bitmap", D2DColor.Goldenrod, this.Font, 180, 800);
bmpGraphics.EndRender();

// draw this device bitmap on screen
g.DrawBitmap(bmpGraphics, this.ClientRectangle);

Note: When creating a Direct2D Device bitmap, do not forget call BeginRender and EndRender method.

Using transform

By calling PushTransform and PopTransform to make a transform session.

g.PushTransform();

// rotate 45 degree
g.RotateTransform(45, centerPoint);

g.DrawBitmap(mybmp, rect);
g.PopTransform();

Examples

Fast images rendering Image Drawing Test See source code

Custom draw on memory bitmap Bitmap Custom Draw See source code

Star space simulation Star Space See source code

Subtitle rendering Subtitle See source code

Whiteboard App whiteboard
See source code

d2dlib's People

Contributors

dependabot[bot] avatar drewnoakes avatar froggiefrog avatar jingwood avatar joakim432710 avatar markhusgenferei avatar nicolasdejong avatar nikeee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

d2dlib's Issues

Using PushTransform/PopTransform on D2DBitmapGraphics object causes Access Violation

Using PushTransform/PopTransform on D2DBitmapGraphics object causes Access Violation

Fix for D2DBitmapGraphics (PushTransform/PopTransform)

public class D2DBitmapGraphics : D2DGraphics, IDisposable
    {
        internal enum D2DTransformType
        {
            Rotate1,
            Rotate2,
            Translate,
            Scale,
            Skew
        }
        
        internal class D2DTransform
        {
            public D2DTransformType Type { get; set; }
            public float Angle { get; set; }
            public D2DPoint Center { get; set; }
            public float X { get; set; }
            public float Y { get; set; }
        }
        
        internal Stack<List<D2DTransform>> TransStack {get; set; }
        
        internal D2DBitmapGraphics(HANDLE handle)
            : base(handle)
        {
            TransStack = new Stack<List<D2DTransform>>();
            TransStack.Push(new List<D2DTransform>());
        }

        public void Dispose()
        {
            D2D.DestoryBitmapRenderTarget(DeviceHandle);

            foreach (var ts in TransStack)
                ts.Clear();
            
            TransStack.Clear();
        }

        public D2DBitmap GetBitmap()
        {
            var bitmapHandle = D2D.GetBitmapRenderTargetBitmap(DeviceHandle);
            return bitmapHandle == HANDLE.Zero ? null : new D2DBitmap(bitmapHandle);
        }

        public override void RotateTransform(float angle)
        {
            TransStack.Peek().Add(new D2DTransform() { Type = D2DTransformType.Rotate1, Angle = angle});
            base.RotateTransform(angle);
        }

        public override void RotateTransform(float angle, D2DPoint center)
        {
            TransStack.Peek().Add(new D2DTransform() { Type = D2DTransformType.Rotate2, Angle = angle, Center = center});
            base.RotateTransform(angle, center);
        }

        public override void TranslateTransform(float x, float y)
        {
            TransStack.Peek().Add(new D2DTransform() { Type = D2DTransformType.Translate, X = x, Y = y});
            base.TranslateTransform(x, y);
        }

        public override void ScaleTransform(float sx, float sy, D2DPoint center = new D2DPoint())
        {
            TransStack.Peek().Add(new D2DTransform() { Type = D2DTransformType.Scale, X = sx, Y = sy, Center = center});
            base.ScaleTransform(sx, sy, center);
        }

        public override void SkewTransform(float angleX, float angleY, D2DPoint center = new D2DPoint())
        {            
            TransStack.Peek().Add(new D2DTransform() { Type = D2DTransformType.Skew, X = angleX, Y = angleY, Center = center});

            base.SkewTransform(angleX, angleY, center);
        }

        public override void ResetTransform()
        {
            TransStack.Peek().Clear();
            base.ResetTransform();
        }

        public override void PushTransform()
        {
            var c = TransStack.Peek().ToList();
            TransStack.Push(c);
        }

        public override void PopTransform()
        {
            if (TransStack.Count == 1)
                throw new InvalidOperationException();
            
            TransStack.Pop();
            
            base.ResetTransform();

            foreach (var t in TransStack.Peek())
            {
                switch (t.Type)
                {
                    case D2DTransformType.Rotate1:
                        base.RotateTransform(t.Angle);
                        break;
                    
                    case D2DTransformType.Rotate2:
                        base.RotateTransform(t.Angle, t.Center);
                        break;
                    
                    case D2DTransformType.Translate:
                        base.TranslateTransform(t.X, t.Y);
                        break;
                    
                    case D2DTransformType.Scale:
                        base.ScaleTransform(t.X, t.Y, t.Center);
                        break;
                    
                    case D2DTransformType.Skew:
                        base.SkewTransform(t.X, t.Y, t.Center);
                        break;
                    
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
        }
    }

Parameter missing in DrawBeziers

I believe there is a missing parameter in D2DGraphics.DrawBeziers - first curve starting point. The D2DBezierSegment contains only two control points and end path point (while you need 4 points for cubic bezier). You use the first control point also as a first main point of cubic bezier:

	context->factory->CreatePathGeometry(&path);
	path->Open(&sink);
	//sink->SetFillMode(D2D1_FILL_MODE_WINDING);
	sink->BeginFigure(bezierSegments[0].point1, D2D1_FIGURE_BEGIN_FILLED); //error - here you should add additional parameter as starting point

load bitmaps on a thread to store them in a list

Hi,

I have been trying out your lib. Very nice!

I have built my own thumbnail viewer in .net. It is very fast due to blitting but I am thinking to use your lib as the backend instead. But I had a question. Can I blit/copy/move and area of the screen to another part of the screen so I only have render the new part?

All the best
Christian

Save a rendered bitmap? (Read back a rendered image)

Hi again!

Once again... Amazing lib 👍

I am trying to find out a way to render the screen to a bitmap (to save it). Cant really figure it out how to do it, can you point me in the right direction?

Thanks
Christian

Clearing a graphics object with D2DColor.Transparent?

Hey man,

It's me again! You know how yesterday you've shown me in the fantastic example that in order to draw like a layer I need to call Graphics.BeginRender(D2DColor.Transparent)?

Well, today I figured out I also need to clear the layer, as in, what happens when you call Graphics.BeginRender(D2DColor.Red), but then with the transparent color.

Is this possible to do without re-creating the graphics object? If so, 'd love to know how!

Regards!

Adding multiple D2DControls is too slow

Hi, I'm trying to add multiple (a hundred) d2dcontrols in my form.

but it's too slow.
It took 4100ms for adding D2DControl and my custom control D2DButton.
But it just took 100ms for adding Button class. (in System.Windows.Forms)

Why it is too slow?
Also I used suspend & resume layout, but it didn't work for me.

I tested in this code (vb.net):

Public Sub TestOnButton(testCount As Integer, useLayout As Boolean)
        Dim rand As New Random()

        If useLayout Then
            Me.SuspendLayout()
        End If

        For i = 1 To testCount
            Dim btn As New TestButton() With {
                    .Text = i.ToString(),
                    .Location = New Point(rand.Next(0, Me.Width), rand.Next(0, Me.Height))
                    }

            Me.Controls.Add(btn)
        Next

        If useLayout Then
            Me.ResumeLayout()
        End If
    End Sub
Imports TestButton = unvell.D2DLib.WinForm.D2DControl
TestOnButton(100, False)

4100ms elapsed

Imports TestButton = System.Windows.Forms.Button
TestOnButton(100, False)

100ms elapsed

thanks.

Can this be used without WPF or WinForms?

Hi, sorry to ask a question here.

I tried to use your Library in a standalone Net5 Console App, but it does not work and the error suggests, that I need to use WPF (or maybe WinForms).
Is that true?
I basically want to render to an Image (.png) and save it, so I would need no GUI.

Import HBitmap directly?

Hi!

I am capture the screen and trying to present the captured image in a D2DImage. Everything works fine, but the question is if it can be more efficient.

Right now I am getting a hBitmap from the Cope screen function, which I convert into a GDI which I send to D2D image which converts it back to an hbitmap?

Do you think there could be an option to feed the hbitmap directly?

success = BitBlt(memoryDc, 0, 0, region.Width, region.Height, desktopDc, region.Left, region.Top, RasterOperations.SRCCOPY Or RasterOperations.CAPTUREBLT)

    D2Dimage.Dispose()
    D2Dimage = Nothing
    D2Dimage = device.CreateBitmapFromGDIBitmap(image.FromHbitmap(bitmap))

Best
Christian

Dim desktophWnd As IntPtr
Dim desktopDc As IntPtr
Dim memoryDc As IntPtr
Dim bitmap As IntPtr
Dim oldBitmap As IntPtr
Dim success As Boolean
'Dim result As Bitmap
desktophWnd = GetDesktopWindow()
desktopDc = GetWindowDC(desktophWnd)
memoryDc = CreateCompatibleDC(desktopDc)
bitmap = CreateCompatibleBitmap(desktopDc, region.Width, region.Height)
oldBitmap = SelectObject(memoryDc, bitmap)

    success = BitBlt(memoryDc, 0, 0, region.Width, region.Height, desktopDc, region.Left, region.Top, RasterOperations.SRCCOPY Or RasterOperations.CAPTUREBLT)


    D2Dimage.Dispose()
    D2Dimage = Nothing
    D2Dimage = device.CreateBitmapFromGDIBitmap(image.FromHbitmap(bitmap))


    SelectObject(memoryDc, oldBitmap)
    DeleteObject(bitmap)
    DeleteDC(memoryDc)
    ReleaseDC(desktophWnd, desktopDc)

Usage of System.Numerics.VectorX

I love this library.

One thing I noticed:
I often need to convert the structs D2DPoint to Vector2.
One reason being that VectorX structs have operator overloading. The other reason is that they support JIT intrinsics and take advantage of SIMD extensions of the CPU, so math operations are much faster with them.

Is it possible to use them directly with this library? Vector2 is basically this struct:

struct Vector2 {
    float x;
    float y;
}

Notice: It does not have the SequentialLayout attribute, so it might be padded during runtime. However, the .NET docs state:

C#, Visual Basic, and C++ compilers apply the Sequential layout value to structures by default. For classes, you must apply the LayoutKind.Sequential value explicitly.

To get an idea, this is the Vector2 implementation:
https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector2.cs

If these structs are ABI compatible, one could just pass them instead of D2DPoint etc. Ist would eliminate conversions as well as increase performance due to hardware acceleration.

Edit:
Matrix3x2 also seems that it has the same binary layout as the one in System.Numerics:
https://github.com/dotnet/runtime/blob/01b7e73cd378145264a7cb7a09365b41ed42b240/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix3x2.cs#L82

Any chances on something in that direction?

Package doesn't appear to work under .NET Core or .NET 5

I've created a new netcoreapp3.1 WinForms app and added a package reference to the latest version of the package.

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
    <Prefer32Bit>true</Prefer32Bit>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="unvell.D2DLib" Version="1.2.2" />
  </ItemGroup>

</Project>

NuGet restore completes succesfully. It doesn't appear to have added any managed assembly references to the compilation, as I see error:

error CS0246: The type or namespace name 'unvell' could not be found (are you missing a using directive or an assembly reference?)

Looking in the obj/project.assets.json file I see:

      "unvell.D2DLib/1.2.2": {
        "type": "package",
        "build": {
          "build/unvell.D2DLib.targets": {}
        }
      },

The .targets file is picked up. I see the linked d2dlib32.dll in the project tree.

image

If I change <TargetFramework> to net4.8, the compilation error goes away. The assets file now shows:

      "unvell.D2DLib/1.2.2": {
        "type": "package",
        "compile": {
          "lib/net20/d2dlibexport.dll": {},
          "lib/net20/d2dwinform.dll": {}
        },
        "runtime": {
          "lib/net20/d2dlibexport.dll": {},
          "lib/net20/d2dwinform.dll": {}
        },
        "build": {
          "build/unvell.D2DLib.targets": {}
        }
      },

For some reason, NuGet is excluding the compile and runtime items when targeting netcoreapp3.1 and net5.0-windows. My guess is the .nuspec file is at fault.

Measuring String

Is it possible to measure a string inside the OnRender of a D2DForm?

Does it support 64 bit?

Does it support 64 bit?
I got this warning when install on x64 project

image

There was a mismatch between the processor architecture of the project being built "AMD64" and the processor architecture of the reference "d2dlibexport, Version=1.2.0.4064, Culture=neutral, processorArchitecture=x86", "x86". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.

PInvokeStackImbalance exceptions

O/S: Windows 10
CPU: 64 bit

Attempting to debug the "BitmapCustomDraw" demo. Targets attempted: "Win32", "x86", and "Mixed Platforms".

Throws multiple exceptions:

Managed Debugging Assistant 'PInvokeStackImbalance'
A call to PInvoke function 'd2dlibexport!unvell.D2DLib.D2D::DrawText' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

[External Code]
d2dlibexport.dll!unvell.D2DLib.D2DGraphics.DrawText(string text, unvell.D2DLib.D2DColor color, string fontName, float fontSize, unvell.D2DLib.D2DRect rect, unvell.D2DLib.DWRITE_TEXT_ALIGNMENT halign, unvell.D2DLib.DWRITE_PARAGRAPH_ALIGNMENT valign) Line 362
	at E:\proj\d2dlib\src\D2DLibExport\D2DGraphics.cs(362)
d2dlibexport.dll!unvell.D2DLib.D2DGraphics.DrawTextCenter(string text, unvell.D2DLib.D2DColor color, string fontName, float fontSize, unvell.D2DLib.D2DRect rect) Line 354
	at E:\proj\d2dlib\src\D2DLibExport\D2DGraphics.cs(354)
Examples.exe!unvell.D2DLib.Examples.Demos.BitmapCustomDraw.BitmapCustomDraw() Line 77
	at E:\proj\d2dlib\src\Examples\Demos\BitmapCustomDraw.cs(77)
[External Code]
Examples.exe!unvell.D2DLib.Examples.DemoSelectionForm..ctor.AnonymousMethod__1_0(object s, System.EventArgs e) Line 72
	at E:\proj\d2dlib\src\Examples\DemoSelectionForm.cs(72)
[External Code]
Examples.exe!unvell.D2DLib.Examples.Program.Main() Line 41
	at E:\proj\d2dlib\src\Examples\Program.cs(41)

stop render on windows7

Hi,

When I restore from lock screen on windows7, it didn't render until restart the program.
I try to get last error code after EndDraw() but it return 0 without any exception.
I also try another library SharpDX sample (BitmapApp), it seens work.
Do you have any idea about this?

Line arrows?

Hi again!

Testing extensively and ran into a question.

Draw arrows at the end or beginning of a line? Is that supported or do I have to draw them myself as triangles?

I am still amazed how easy this library is to use to get crazy much more performance. Thanks for creating it!

Christian

Rendering a transparent cleared image over another removes the original image?

Hey there,

It's me again, hopefully not bothering you with this one. It appears that when I render an image cleared using the Graphics.Clear method over another image, it removes the original image.

                   e.Graphics.DrawBitmap(
                        Snippit.Image,
                        new D2DRect(0, 0, form.DesktopBounds.Width, form.DesktopBounds.Height),
                        new D2DRect(form.DesktopBounds.Left, form.DesktopBounds.Top, form.DesktopBounds.Width, form.DesktopBounds.Height)
                    );
                    /*e.Graphics.FillRectangle(
                        new D2DRect(
                            form.DisplayRectangle.Left,
                            form.DisplayRectangle.Top,
                            form.DisplayRectangle.Width,
                            form.DisplayRectangle.Height
                        ),
                        overlayColor
                    );*/
                    e.Graphics.DrawBitmap(
                        Canvas,
                        new D2DRect(0, 0, form.DesktopBounds.Width, form.DesktopBounds.Height),
                        new D2DRect(form.DesktopBounds.Left, form.DesktopBounds.Top, form.DesktopBounds.Width, form.DesktopBounds.Height)
                    );

I should be seeing the Snippit.Image as the background, but instead I'm recieving a gray-ish looking color with the Canvas on top of it.

image

I've already double checked if the image I'm overlaying is actually transparent, and it is.

This is the image being overlayed.
hello

This might be a bug within the API I'm not sure.

      if (Canvas == null || Canvas.Width != Snippit.Image.Width && Canvas.Height != Snippit.Image.Height)
         {
             Canvas?.Dispose();
             CanvasGraphics?.Dispose();

             Canvas = new Bitmap(
                 Snippit.Image.Width,
                 Snippit.Image.Height
             );

             CanvasGraphics = Graphics.FromImage(Canvas);
             CanvasGraphics.CompositingQuality = CompositingQuality.HighQuality;
             CanvasGraphics.SmoothingMode = SmoothingMode.HighQuality;
             CanvasGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
         }

         CanvasGraphics.Clear(Color.Transparent);

         Canvas.Save("hello.png");

Regards,

  • Eddie

Inverse Matrix

Is it possible to invert matrix ? ( C# lib ). Actually i'm drawing rectangles, and using Translate and Scale to allow Pan & Zoom. Thats working, but i can't calculate mouse position because the rectangles positions changed via the Matrix translate but there is no way to also translate mouse pos (or i didn't find how).

Performance idea

Hi!

An idea which might be wrong for D2D but for GDI+ drawing a line is very expensive. Since most time you draw a straight line, vertical or horizontal I figured out that instead of using draw line, drawing a 1pixel rectangle is 5x faster than draw line.

Not sure if it is the same case here but if, it could be interesting with a “drawlinevertical” and “drawlinehorisontal” function which simply
Wraps the draw rectangle function.

Best
Christian

Memory exception when loading transparent bitmap

When I try to render a PNG with an alpha channel, I get an access violation exception.

I do something like this:

Dim Thing As New Bitmap("filename.png")
Dim bmp = Device.CreateBitmapGraphics(screenImageWidth, screenImageHeight)
bmp.beginrender
bmp.DrawBitmap(Thing, New D2DRect(0, 0, Thing.Width - 1, Thing.Height - 1), 1, True, D2DBitmapInterpolationMode.Linear)
bmp.endrender

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

If I just change that one value to False to not show alpha, it works, but of course the bitmap shows no transparency layer.

Any idea how to fix that? Or an alternate way to load a PNG with an alpha channel and render it properly?

I really appreciate the effort you have done here. Since MSFT stopped supporting DX in VB it has crippled my efforts to do some projects.

High DPI support

Currently, only support a default DPI 96, there should be APIs available to support variable DPI settings.

Related to #26

DrawRectangle not drawing anything

Using method DrawRectangle doesn't generate any results

Fix for d2dlib (FillRectangle)

void DrawRectangle(HANDLE handle, D2D1_RECT_F* rect, D2D1_COLOR_F color,
	FLOAT width, D2D1_DASH_STYLE dashStyle)
{
	D2DContext* context = reinterpret_cast<D2DContext*>(handle);

	ID2D1SolidColorBrush* brush = NULL;
	ID2D1StrokeStyle* strokeStyle = NULL;

	context->renderTarget->CreateSolidColorBrush(color, &brush);

	if (brush != NULL) {
		if (dashStyle != D2D1_DASH_STYLE_SOLID)
		{
			context->factory->CreateStrokeStyle(D2D1::StrokeStyleProperties(
				D2D1_CAP_STYLE_FLAT,
				D2D1_CAP_STYLE_FLAT,
				D2D1_CAP_STYLE_ROUND,
				D2D1_LINE_JOIN_MITER,
				10.0f,
				dashStyle,
				0.0f), NULL, 0, &strokeStyle);
		}

		context->renderTarget->DrawRectangle(rect, brush, width, strokeStyle);
	}

	SafeRelease(&strokeStyle);
	SafeRelease(&brush);
}

Release latest Version

Amazing library!

Would it be possible to release the latest version on NuGet? My current project depends on some of the new features.

Text Performance

Hello, i noticed that Text rendering is fairly slow. I found a work-around by creating bitmap and rendering the text on it once and then rendering the bitmap. This is working but maybe there is another way to have better text rendering performance ?
To be more clear, i'm creating a Node-Based graph and so each nodes may need to have 1 or more text, and this clearly degrade performance when more and more nodes are added.

Draw Transparent shape over transparent WinForm

Can say how much I liked your lib. Thanks indeed!

I come up to hide a winform window and tried to draw semitransparent shapes over, but it didn't work so well.
see this quick code.

public class TransientWindow : D2DForm
    {
        public TransientWindow()
        {
            BackColor = System.Drawing.Color.FromArgb(255, 255, 255, 255);
            TransparencyKey = BackColor;
            FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            AllowTransparency = true;
        }

        protected override void OnRender(D2DGraphics g)
        {
            g.Clear(D2DColor.FromGDIColor(BackColor));

            g.FillRectangle(50, 50, 500, 500, new D2DColor(.1f, D2DColor.CornflowerBlue));
            g.DrawText("This is a test", new D2DColor(.2f, D2DColor.Red), "Arial", 20, 50, 50);
        }
    }

image

not sure if it is to draw a bitmap of the shape area, that to be used as a background to the shape to simulate transperency? seems too expensive.

Thoughts?

Fillpolygon does not work

Hi!

Created an array of D2Dpoints and try to draw it.

drawpolygon works fine
But fillpolygon causes that nothing is being rendered at all. Does not get an error message.

Any ideas why it happens?

Best
Christian

Custom Dash Styles for DrawRectangle

It seems that DrawRectangle can only be used with a specific Color.

In GDI, we can also use a Pen to draw a rectangle. This Pen as a DashPattern property as well as some other properties that change the behaviour of the Pen (for example, DashOffset).
The DashPattern can be used to draw dashed lines. And when used for DrawRectangle, we get a dahsed rectangle.

Is it possible to do this with Direct2D aswell? I'd use this feature in my current application.

I see that there is a D2DDashStyle we can pass to DrawRectangle. Is there a way to provide a custom dash pattern or a dash offset?

Edit:
I found this Direct2D api for that:
https://docs.microsoft.com/en-us/windows/win32/direct2d/how-to-draw-an-ellipse#draw-an-ellipse-with-a-dashed-stroke
This example shows how to create a custom dash pattern:
https://docs.microsoft.com/en-us/windows/win32/api/d2d1/ne-d2d1-d2d1_dash_style#remarks

LinearGradientBrush cause memory leak

I found that the memory always get more and more when creating a new component by using LinearGradientBrush for background painting, even the component already disposed.
I try to figure out what cause this problem.

There is probably a reason that.
While using CreateLinearGradientBrush() function in Brush.cpp., it calls CreateGradientStopCollection before CreateLinearGradientBrush but (what ?) did not release it.

Inverse Matrix in the Demo does not work when scaling

Hi, i used the Matrix3 provided in the Demo but when scaling it, the inverse matrix does not work, or maybe i'm doing it wrong . Here is how i update my matrix

Matrix.LoadIdentity();
Matrix.Scale(ViewZoom, ViewZoom);
Matrix.Translate(ViewPosition.X, ViewPosition.Y);
InverseMatrix.CopyFrom(Matrix).Inverse();

Memory leak in CreateBitmapFromGDIBitmap()

I'm using this library for a project that opens and closes a D2DForm often. It uses GDI bitmaps to cache because they are expensive to create and I don't want to wait for that when opening the window.

I noticed the equivalent of the code below leads to a memory leak. The below code should, if I understand it correctly, have the same memory use before and after. Unfortunately that seems not to be the case:

Bitmap bitmap = new Bitmap(1000, 1000);
D2DBitmap d2dBitmap = Device.CreateBitmapFromGDIBitmap(bitmap);
d2dBitmap.Dispose();
bitmap.Dispose();

Is this a memory leak or am I doing something wrong and is there another way to reclaim the used memory? Perhaps there is a workaround?

Try to support Direct2D 1.1

Considering upgrade the API from Direct2D 1.0 to Direct2D 1.1 in order to support more excellent features and effects.

Pros.

  • More excellent features and effects available
  • Rendering support for Windows Store apps *1

Cons.

  • Can't support the old Windows platforms (Windows 7 without update package and older)
  • Performance degradation?

Resources

All suggestions are welcome.


Building x64 does not copy d2dlib64.dll to Examples output

  1. Open d2dlib.sln as from github
  2. Set target to Debug, x64.
  3. Build solution.
  4. Set Examples as startup project, execute.
  5. Click on any demo.

Exception: d2dlib64.dll missing.
Look at src\examples\bin\x64\debug folder: d2dlib64.dll is not there.

Open path

The library is fantastic, thank you for that. I have a little problem with the ClosePath - I can't specify, whether the path should be opened or closed (as it is possible using D2D1_FIGURE_END in D2D). It's impossible to draw bezier cubic curves like this (the first point is always connected to end point).

Also there is a crash/hang, when I don't call ClosePath and I'm trying to draw geometry. E.g.:

var path = crc.GR.Device.CreatePathGeometry();
path.SetStartPoint(new D2DPoint(0, 0.5f));

D2DBezierSegment seg1 = new D2DBezierSegment()
{
  point1 = new D2DPoint(0.25f, 0),
  point2 = new D2DPoint(0.75f, 1),
  point3 = new D2DPoint(1, 0.5f),
};
path.AddBeziers(new D2DBezierSegment[] { seg1 });
path.ClosePath(); //if I don't add this line, the application hangs

graphics.DrawPath(path, D2DColor.AliceBlue, 2 * pixelSize);

Suggestion: Add Direct2D counterparts for GetPixel, SetPixel and Graphics.FromImage

I need to pick a color from a bitmap, but the GetPixel function only exists in the default Bitmap class. Also graphics from image would allow drawing on top of an existing bitmap and not creating a blank one, which Device.CreateBitmapGraphics is doing.

Edit: You can make an empty graphic and draw the bitmap on it, but I meant that you can't directly edit the existing bitmap, just paste it onto the graphic, and there's no way to get the result back.

Draw Pie Chart?

Hi!

I have tried to figure a way to draw a PIE Chart but without success. Could anyone help to point me in a direction of how to do that? Would like to fill the pie charts, not just draw the line.

Thanks...
Christian

d2dlibexport - missing dll reference

I think your latest commit of binaries has some issues. When I use these, I get a reference error, where d2dlibexport is complaining about a missing reference (d2dlib.dll). When I place your previous version, there is no errors.

Is it possible to create a graphics object from a bitmap?

Hey there man!

Been studying your code a bit and I've cleaned a lot up (for instance, the control can now be dragged and dropped into the forms.) I'm using your code to create a control that has multiple layers like you would have in photoshop or other editing software, the only issue is that I can not create a graphics object from a bitmap.

var IntPtr = _Canvas.GetHbitmap(); var Device = D2DDevice.FromHwnd(IntPtr); CanvasGraphics = Device.CreateBitmapGraphics();

System.AccessViolationException HResult=0x80004003 Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Source=<Cannot evaluate the exception source> StackTrace: <Cannot evaluate the exception stack trace>

So before I rewrite the layers to be D2DControls instead of Bitmaps I'd like to ask if you could help out enabling me to create this feature for bitmaps (if that's even possible.)

This makes an absolutely amazing alternative to graphics and I'd have no problem slowly piecing it together until it is. Provided is my copy of your source code - including "DrawingPanel.cs" which will eventually be the layered panel.

If this project is too old and you wish to not continue it I'd be glad to take it over from you.

Snipper DirectDraw.zip

Usage of D2DLib

Hi!

I just wanted to give you a link back to the product I developed with the help of your library. We call it POPS and it is a software to make online presentations much more interesting. It would have been impossible to develop without this library.

Try it out, we give away it for free :) and thank you for a great lib!

https://www.paliscope.com/products/pops-beta/

Best
Christian

Drawing a bitmap in a circle?

Hi!

Great lib. Just starting to convert my controls to use this. Love it!

I am trying to draw a bitmap inside a circle. Would that be possible?

Thanks
Christian

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.