C# 改进了C-GDI中的循环绘制
我有一个for循环,需要调用graphics.DrawLine运行200000次。这是非常缓慢的,我期待着您的帮助,以提高这个循环的性能。当我尝试使用TaskParallelism时,它会给出错误消息,调用线程必须是STA,因为许多UI组件都需要它。我还尝试将循环拆分为两个并并行执行,这也会导致相同的错误。我已经删除了与该尝试相关的代码,并给出了实际代码,该代码必须针对性能进行优化 代码是 //从arraylist获取数据,arraylist是图形的数据点C# 改进了C-GDI中的循环绘制,c#,winforms,gdi,C#,Winforms,Gdi,我有一个for循环,需要调用graphics.DrawLine运行200000次。这是非常缓慢的,我期待着您的帮助,以提高这个循环的性能。当我尝试使用TaskParallelism时,它会给出错误消息,调用线程必须是STA,因为许多UI组件都需要它。我还尝试将循环拆分为两个并并行执行,这也会导致相同的错误。我已经删除了与该尝试相关的代码,并给出了实际代码,该代码必须针对性能进行优化 代码是 //从arraylist获取数据,arraylist是图形的数据点 Graphics g = nu
Graphics g = null;
public Drawing(Graphics _g, DrawingData _Data)
{
g = _g;
drawingData = _Data;
}
private void FrameDrawLine1()
{
DataValueSet pds = null;
DataValueSet ds = null;
for (int i = 1; i < drawingData.data.Count; i++) // the count will be 100,000
{
ds = (DataValueSet)drawingData.data[i];
PlotColumne(pds, ds);
}
}
//在图中画线
private void drawLine(Color color, double xFrom, double xTo, double yFrom, double yTo,
bool interpolate, int lineWidth)
{
try
{
System.Windows.Shapes.Line newline = new System.Windows.Shapes.Line();
Pen linePen = new Pen(new SolidBrush(color), lineWidth);
float x1 = (float)xFrom;
float x2 = (float)xTo;
float y1 = (float)yFrom;
float y2 = (float)yTo;
if (interpolate)
{
g.DrawLine(linePen, x1, y1, x2, y2);
}
else
{
g.DrawLine(linePen, x1, y1, x2, y1);
g.DrawLine(linePen, x2, y1, x2, y2);
}
}
catch (Exception ex)
{
GenericFunctions.ErrorMessage("Error has occured while drawing graph lines. Please try again.");
}
}
你应该试着画一幅图像。为此,您需要从位图创建自己的图形上下文
Bitmap yourBitmap = new Bitmap(your controls width, height, PixelFormat. Format32bppArgb)
GRAPHICS G = Graphics.FromImage(yourBitmap)
// Draw your lines here
最后,必须使用控件的原始图形上下文绘制图片。
e、 Graphics.DrawImageUnscaled0,0,你的位图
此外,还可以调整图形上下文的参数。它们对性能也有很大的影响
这里有一个指向这些参数的链接:嗯,你刚开始在drawLine中使用g,它从哪里来?不要计算你应该在什么时候绘制。当所依赖的数据发生变化时,只需进行一次计算,然后根据计算结果绘制一组线。您将无法并行化渲染部分,因为您遇到了一个异常:如果要在屏幕上绘制,则必须在一个UI线程中绘制。即使绘制到屏幕外位图,绘制线程之间的同步也是一个很大的瓶颈。
private void drawLine(Color color, double xFrom, double xTo, double yFrom, double yTo,
bool interpolate, int lineWidth)
{
try
{
System.Windows.Shapes.Line newline = new System.Windows.Shapes.Line();
Pen linePen = new Pen(new SolidBrush(color), lineWidth);
float x1 = (float)xFrom;
float x2 = (float)xTo;
float y1 = (float)yFrom;
float y2 = (float)yTo;
if (interpolate)
{
g.DrawLine(linePen, x1, y1, x2, y2);
}
else
{
g.DrawLine(linePen, x1, y1, x2, y1);
g.DrawLine(linePen, x2, y1, x2, y2);
}
}
catch (Exception ex)
{
GenericFunctions.ErrorMessage("Error has occured while drawing graph lines. Please try again.");
}
}
Bitmap yourBitmap = new Bitmap(your controls width, height, PixelFormat. Format32bppArgb)
GRAPHICS G = Graphics.FromImage(yourBitmap)
// Draw your lines here