本文来告诉大家如何在 Direct2D1 绘制基本图形,包括线段、矩形、椭圆
本文是一个系列
本文的组织参考Direct2D,对大神表示感谢。
在开始前先告诉大家为何需要使用 Direct2D ,虽然 WPF 也是基于 DX 进行渲染,但是 WPF 做了很多兼容处理,所以没有比直接使用 Direct2D 的性能高。经过测试,在使用下面的所有代码,占用 CPU 几乎都是 0% ,因为没有布局、透明和事件处理,所以速度是很快。
点
在 Direct2D 使用的 点是 Point2F ,传入的是两个 float ,和 Point 差不多。
Point2F 也是一个结构体,所以和 Point 类型差不多
线段
线段需要使用 DrawLine ,方法的签名
public void DrawLine(Point2F firstPoint 起始点 , Point2F secondPoint 终点, Brush brush 笔刷, float strokeWidth 线段宽度)
public unsafe void DrawLine(Point2F firstPoint, Point2F secondPoint, Brush brush, float strokeWidth, StrokeStyle strokeStyle 线段样式)
所以使用下面的方法就可以在 (10,10) (100,10) 画出一条宽度为 2 的红线
_renderTarget.DrawLine(new D2D.Point2F(10, 10), new D2D.Point2F(100, 10),
_renderTarget.CreateSolidColorBrush(new D2D.ColorF(1, 0, 0, 1)), 2);
上面的代码运行在WPF 使用 Direct2D1 画图入门文章的 OnRendering 方法,为了让大家也可以试试下面的代码,建议大家先去看这篇博客。
关于笔刷会在后面说
StrokeStyle
可以看到上面线段的最后一个参数是 StrokeStyle 那么这个参数是如何创建?在 Direct2D 有很多类都不能直接直接创建需要使用 D2DFactory 或 RenderTarget 才能创建。StrokeStyle 就需要使用 D2DFactory 进行创建。
创建 StrokeStyle 需要参数 StrokeStyleProperties,这个类的构造有两个重载,一个是不需要参数,另一个是需要很多参数。代码请看下面。
public StrokeStyleProperties(CapStyle startCap, CapStyle endCap, CapStyle dashCap, LineJoin lineJoin, float miterLimit, DashStyle dashStyle, float dashOffset)
从代码的命名大概大家也可以知道 StrokeStyleProperties 参数的意思,下面先创建一个没有构造函数的来创建 StrokeStyle ,请看下面代码
var strokeStyleProperties = new D2D.StrokeStyleProperties();
var strokeStyle = d2DFactory.CreateStrokeStyle(strokeStyleProperties);
_renderTarget.BeginDraw();
_renderTarget.DrawLine(new D2D.Point2F(10,10),new D2D.Point2F(100,10), _renderTarget.CreateSolidColorBrush(new D2D.ColorF(1, 0, 0, 1)),2, strokeStyle);
_renderTarget.EndDraw();
需要注意,创建 strokeStyle 的工厂需要和创建 RenderTarget 一样,如果使用不一样的工厂就会出现下面异常。
Microsoft.WindowsAPICodePack.DirectX.Direct2D1.Direct2DException:“EndDraw has failed with error