我在 Microsoft Visual Studio 2010 Express for Windows Phone 中编写代码。我需要在 Canvas
上添加一个点,但我不能...
for (float x = x1; x < x2; x += dx)
{
Point poin = new Point();
poin.X = x;
poin.Y = Math.Sin(x);
canvas1.Children.Add(poin);
}
工作室说:
Error 2 Argument 1: cannot convert from 'System.Windows.Point' to 'System.Windows.UIElement'
我的问题是:如何在 Canvas
上添加一个点?
最佳答案
根据您的代码片段,我假设您正在尝试绘制一条曲线。为此,您可以查看 GraphicsPath
。您可以使用这些点作为坐标,而不是绘制单个点,通过线将它们连接起来。然后,在您的代码中,您可以使用 AddLine
方法创建一个 GraphicsPath
。
例如,这可以绘制到位图上。
编辑
示例(未测试):
GraphicsPath p = new GraphicsPath();
for (float x = x1; x < x2; x += dx)
{
Point point = new Point();
point.X = x;
point.Y = Math.Sin(x);
Point point2 = new Point();
point2.X = x+dx;
point2.Y = Math.Sin(x+dx);
p.AddLine(point, point2);
}
graphics.DrawPath(p);
另一种方法是使用 WPF Path
类,它的工作原理大致相同,但它是一个真正的 UI 元素,您可以将其添加到 Canvas
.
编辑
有人指出,上面的代码是 Windows Forms 代码。那么,您可以在 WPF 中执行以下操作:
myPolygon = new Polygon();
myPolygon.Stroke = System.Windows.Media.Brushes.Black;
myPolygon.Fill = System.Windows.Media.Brushes.LightSeaGreen;
myPolygon.StrokeThickness = 2;
myPolygon.HorizontalAlignment = HorizontalAlignment.Left;
myPolygon.VerticalAlignment = VerticalAlignment.Center;
PointCollection points = new PointCollection();
for (float x = x1; x < x2; x += dx)
{
Point p = new Point(x, Math.Sin(x));
points.Add(p);
}
myPolygon.Points = points;
canvas1.Children.Add(myPolygon);
关于c# - 添加点到 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8911713/