Custom line drawing in WPF
I'm trying to manually draw a line in WPF by overriding the OnRender method of a control and calling the DrawLine method on the given DrawingContext. I read somewhere that this method call doesn't instantly draw the line, but I can't work out how to actually cause the line to appear.
I've tried using a combination of PathGeometry, LineSegments, Line and Polyline controls. I could draw what I wanted then, but offsets weren't quite right (i.e. when drawing a line, it was fine, when drawing a polyline, everything became incorrectly offset).
Any advice on this would be great.
EDIT
Pen Code
private static readonly Pen LinePen = new Pen(new SolidColorBrush(Colors.Green), 3.0d);
private static readonly Pen WayPointPen = new Pen(new SolidColorBrush(Colors.Gray), 3.0d);
Render Code
protected override void OnRender(DrawingContext drawingContext)
{
// Draw way points
this.DrawWayPoints(drawingContext);
if (mDrawing)
{
// Draw current line
this.DrawCurrentLine(drawingContext);
}
}
private void DrawCurrentLine(DrawingContext context)
{
if(mStartPoint.HasValue && mEndPoint.HasValue)
{
// Draw the line
context.DrawLine(开发者_开发问答LinePen, mStartPoint.Value, mEndPoint.Value);
}
}
private void DrawWayPoints(DrawingContext context)
{
if (mWayPoints.Count < 2)
{
return;
}
// Draw all points
for (int i = 0; i < mWayPoints.Count - 1; i++)
{
var start = mWayPoints[i];
var end = mWayPoints[i + 1];
// Draw the line
context.DrawLine(WayPointPen, start, end);
}
}
EDIT
Test Project: http://dl.dropbox.com/u/12763956/DrawingTest.zip (Test Project written in Visual Studio 2010)
Usage: - Left click within the raised area to add points to the list. - Right click to end drawing and clear points.
Note: Custom drawn lines (in OnRender override) do not appear.
There are actually two issues here. The first is your Canvas's Background covers up anything you'd draw on your DrawingControl. So if you set the Canvas Background to Transparent, you can temporarily work around that issue.
The second issue is you need to call InvalidateVisual after you add a point to your collection to force it to redraw.
You would probably need to add another control that appears on top of the Canvas, and render the lines there. Or you'd need to render the Background yourself in the DrawingControl.OnRender method.
精彩评论