You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SharpDX.Direct2D1中绘制带ColorMatrix的彩色多边形图像

在SharpDX.Direct2D1中实现带ColorMatrix的多边形图像绘制

实现方案

完全可以实现,核心思路是将ColorMatrix滤镜处理后的图像作为ImageBrush的输入,再用该画刷填充目标多边形,同时通过ImageBrush的变换属性控制图像在多边形内的UV坐标映射。

具体实现代码及说明

修改后的完整代码

// 开始绘制流程
d2dContext.Target = d2dTarget;
d2dContext.BeginDraw();
d2dContext.Clear(new RawColor4(0.9f, 0.9f, 0.9f, 1));

// 1. 用ColorMatrix滤镜处理原始图像
SharpDX.Direct2D1.Effects.ColorMatrix colorEffect = new SharpDX.Direct2D1.Effects.ColorMatrix(d2dContext);
colorEffect.Matrix = zzzGetColorMultiplyMatrix(Color.FromArgb(255, 0, 255, 0), 0.7f); // 示例:绿色叠加效果
colorEffect.SetInput(0, imgTest1, false);

// 2. 创建带色彩效果的ImageBrush,配置UV映射参数
var imageBrushProps = new SharpDX.Direct2D1.ImageBrushProperties
{
    ExtendModeX = SharpDX.Direct2D1.ExtendMode.Wrap,
    ExtendModeY = SharpDX.Direct2D1.ExtendMode.Wrap,
    InterpolationMode = SharpDX.Direct2D1.InterpolationMode.Linear,
    SourceRectangle = new RawRectangleF(0, 0, imgTest1.Size.Width, imgTest1.Size.Height),
    // 通过Transform控制UV坐标:示例为缩放+平移,可按需调整矩阵
    Transform = new RawMatrix3x2(
        0.5f, 0f,          // X轴缩放比例
        0f, 0.5f,          // Y轴缩放比例
        20f, 10f           // UV空间平移偏移
    )
};
// 传入ColorMatrix处理后的图像作为画刷源
var coloredImageBrush = new SharpDX.Direct2D1.ImageBrush(d2dContext, colorEffect.Output, imageBrushProps);

// 3. 定义闭合多边形路径
SharpDX.Direct2D1.PathGeometry polygonGeo = new SharpDX.Direct2D1.PathGeometry(d2dContext.Factory);
using (SharpDX.Direct2D1.GeometrySink geoSink = polygonGeo.Open())
{
    geoSink.BeginFigure(new RawVector2(400 + 80, 310), SharpDX.Direct2D1.FigureBegin.Filled);
    geoSink.AddLine(new RawVector2(500 + 80, 310));
    geoSink.AddLine(new RawVector2(500 + 80, 360));
    geoSink.AddLine(new RawVector2(400 + 80, 360)); // 补全闭合边,避免填充异常
    geoSink.EndFigure(SharpDX.Direct2D1.FigureEnd.Closed);
    geoSink.Close();
}

// 4. 用带色彩效果的画刷填充多边形
d2dContext.FillGeometry(polygonGeo, coloredImageBrush);

// 资源释放(实际项目中需确保所有IDisposable对象都被正确释放)
coloredImageBrush.Dispose();
polygonGeo.Dispose();
colorEffect.Dispose();

// 结束绘制
d2dContext.EndDraw();
swapChain.Present(1, PresentFlags.None);

关键细节说明

  • ColorMatrix与ImageBrush结合:不能直接通过DrawImage将滤镜图像绘制到多边形区域,需将处理后的图像作为画刷输入,通过FillGeometry实现区域填充。
  • UV坐标控制:ImageBrush的Transform矩阵直接对应UV空间的变换,缩放矩阵可调整图像在多边形内的拉伸/重复程度,平移矩阵可偏移图像位置,旋转矩阵则能实现图像的旋转映射。
  • 路径闭合:必须确保多边形路径是完全闭合的,否则填充可能出现边缘异常(原代码中的triangGeo3缺少一条闭合边,已在修改代码中补全)。

内容的提问来源于stack exchange,提问作者Avatar256

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:45:30