gpt4 book ai didi

winforms - 绘制渐变矩形的有效方法

转载 作者:行者123 更新时间:2023-12-03 05:13:38 27 4
gpt4 key购买 nike

我正在生成一堆具有不同大小和位置的 RectangleF 对象。在 GDI+ 中用渐变画笔填充它们的最佳方法是什么?

在 WPF 中,我可以创建一个 LinearGradientBrush,设置开始和结束相对点,WPF 将处理其余的事情。

但是在 GDI+ 中,渐变画笔构造函数需要绝对坐标中的位置,这意味着我必须为每个矩形创建一个画笔,这将是一个非常复杂的操作。

我错过了什么还是这确实是唯一的方法?

最佳答案

如果您只想声明画笔一次,则可以在应用渐变之前指定变换。请注意,使用转换将覆盖许多可以在 LinearGradientBrush 上指定的构造函数参数。

LinearGradientBrush.Transform Property (System.Drawing.Drawing2D)

要修改变换,请调用画笔对象上与所需矩阵运算相对应的方法。请注意,矩阵运算不可交换,因此顺序很重要。出于您的目的,您可能希望对矩形的每次呈现按以下顺序执行这些操作:缩放、旋转、偏移/平移。

LinearGradientBrush.ResetTransform Method @ MSDN

LinearGradientBrush.ScaleTransform Method (Single, Single, MatrixOrder) @ MSDN

LinearGradientBrush.RotateTransform Method (Single, MatrixOrder) @ MSDN

LinearGradientBrush.TranslateTransform Method (Single, Single, MatrixOrder) @ MSDN

请注意,系统级绘图工具实际上并不包含渐变画笔的库存定义,因此,如果您对制作多个画笔有性能问题,那么创建多个渐变画笔的开销不应超过GDI+/System.Drawing 维护定义渐变和样式所需的数据。您可能会根据需要为每个矩形创建一个画笔,而不必深入研究通过变换自定义画笔所需的数学。

Brush Functions (Windows) @ MSDN

以下是您可以在 WinForms 应用程序中测试的代码示例。此应用程序使用 45 度梯度的渐变画笔绘制图 block ,缩放到图 block 的最大尺寸(简单计算)。如果您摆弄值和变换,您可能会发现,如果您有不平凡的渐变定义,则不值得使用为所有矩形设置变换的技术。否则,请记住,您的转换是在世界级别应用的,在 GDI 世界中,y 轴是颠倒的,而在笛卡尔数学世界中,它是从下到上排序的。这也会导致角度顺时针应用,而在三角学中,当 y 轴向上时,角度会逆时针方向增加值。

using System.Drawing.Drawing2D;

namespace TestMapTransform
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle rBrush = new Rectangle(0,0,1,1);
Color startColor = Color.DarkRed;
Color endColor = Color.White;
LinearGradientBrush br = new LinearGradientBrush(rBrush, startColor, endColor, LinearGradientMode.Horizontal);

int wPartitions = 5;
int hPartitions = 5;

int w = this.ClientSize.Width;
w = w - (w % wPartitions) + wPartitions;
int h = this.ClientSize.Height;
h = h - (h % hPartitions) + hPartitions;

for (int hStep = 0; hStep < hPartitions; hStep++)
{
int hUnit = h / hPartitions;
for (int wStep = 0; wStep < wPartitions; wStep++)
{
int wUnit = w / wPartitions;

Rectangle rTile = new Rectangle(wUnit * wStep, hUnit * hStep, wUnit, hUnit);

if (e.ClipRectangle.IntersectsWith(rTile))
{
int maxUnit = wUnit > hUnit ? wUnit : hUnit;

br.ResetTransform();
br.ScaleTransform((float)maxUnit * (float)Math.Sqrt(2d), (float)maxUnit * (float)Math.Sqrt(2d), MatrixOrder.Append);
br.RotateTransform(45f, MatrixOrder.Append);
br.TranslateTransform(wUnit * wStep, hUnit * hStep, MatrixOrder.Append);

e.Graphics.FillRectangle(br, rTile);

br.ResetTransform();
}
}
}
}

private void Form1_Resize(object sender, EventArgs e)
{
this.Invalidate();
}
}
}

这是输出的快照:

5x5 Form with Gradient-Tile Painting

关于winforms - 绘制渐变矩形的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15073939/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com