WPF 使用 Direct2D1 画图 绘制基本图形

本文详细介绍了如何在WPF中利用Direct2D1进行基本图形的绘制,包括点、线段、矩形、椭圆和文字。讲解了DrawLine、DrawRectangle、DrawEllipse等方法的使用,以及StrokeStyle和StrokeStyleProperties的设置,阐述了Direct2D1相对于WPF的性能优势,并提供了示例代码。
摘要由CSDN通过智能技术生成

本文来告诉大家如何在 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值