在WPF中绘制大量数量的线段时,绘制很慢,而且很耗CPU的资源。绘制到几百条线段时,就会明显无法交互操作。
通过查询资料,我们找到一个方法可以解决:使用StreamGeometry在内存中绘制,然后再Render到WPF的控件上。
实现如下:
using (var geometryContext = _cueGeometry.Open())
using (var perContext = _perGeometry.Open())
using (var _volContext = _volGeometry.Open())
{
for (int i = 0; i < TickLineValue.drawTickData.Count() - 1; i++)
{
TickLineValue.drawTickData[i].picTopY = topY;
TickLineValue.drawTickData[i].PriceMax = TickLineValue.tickMaxValue;
TickLineValue.drawTickData[i].PriceMin = TickLineValue.tickMinValue;
TickLineValue.drawTickData[i].ScreenTickHeight = TickLineValue.tickHeight;
TickLineValue.drawTickData[i].VolMax = TickLineValue.volMaxValue;
TickLineValue.drawTickData[i].picVolTopY = TickLineValue.lineObject.GetYValue() + TickLineValue.perPicTxtHeight;
TickLineValue.drawTickData[i].ScreenVolHeight = TickLineValue.volHeight;
//绘制图形的
x = TickLineValue.picLeftWidth + i * TickLineValue.picWidth;
//绘制tick
Point p0 = new Point();
p0.X = x;
p0.Y = TickLineValue.drawTickData[i].newPriceY;
if (i == 0)
{
geometryContext.BeginFigure(p0, true, false);
}
else
{
geometryContext.LineTo(p0, true, true);
}
//绘制均线
p0.Y = TickLineValue.drawTickData[i].perPriceY;
if (i == 0)
{
perContext.BeginFigure(p0, true, false);
}
else
{
perContext.LineTo(p0, true, true);
}
////绘制交易量
p0.Y = TickLineValue.drawTickData[i].tradeVolY;
Point p1 = new Point();
p1.X = x;
p1.Y = volY;
_volContext.BeginFigure(p0, true, false);
_volContext.LineTo(p1, true, true);
//绘制时间
strTime = TickLineValue.drawTickData[i].dateTime;
strTime = dealTimeString(strTime, oldTime);
if (strTime == "")
{
continue;
}
oldTime = strTime;
FormattedText t = new FormattedText(strTime, System.Globalization.CultureInfo.InvariantCulture,
FlowDirection.LeftToRight, new Typeface(fontFamily.ToString()), TickLineValue.timeFontSize,
timeB);
if (oldX
p0.Y = timeY;
dc.DrawText(t, p0);
oldX = p0.X + t.Width;
}
}
}
dc.DrawGeometry((Brush)null, tickPen, _cueGeometry);
dc.DrawGeometry((Brush)null, perPen, _perGeometry);
dc.DrawGeometry((Brush)null, volPen, _volGeometry);
}
catch (Exception ex)
{
TickLineValue.picErrorLog.log(5, "TickPictureCanvas|DrawPicTick|" + ex.ToString());
}
}
如果是连续的曲线,那么就使用一次BeginFigure(p0, true, false);如果是每次都是独立的线段,那么
就可以多次使用:BeginFigure(p0, true, false);