我找到了使用<DrawingBrush TileMode="Tile">
的方法,但是不允许创建渐变,因为这会产生许多重复的正方形。也许有什么方法可以动态地做到这一点,而不是在xaml中?
答案 0 :(得分:1)
我不得不做一些非常相似的事情,并选择用C#动态创建一个网格,该方法在Canvas加载的事件上被调用。
“ max_value”是您希望网格成为的最大像素大小,我将我的像素设置为3500。
“ ScaleFactor”是线之间的间距/正方形的大小,我将我的值设置为15。
“画布”就是您也要应用网格的画布。
我确实必须提取代码并从一个较大的程序中对其进行调整,但是它仍然可以工作,但是我目前没有IDE对其进行测试。
class GridLine //Declares a grid-line object
{ //Declares a variety of different line lists, used for different parts of the grid.
private List<Line> XGridline { get; set; } = new List<Line>();
private List<Line> YGridline { get; set; } = new List<Line>();
private Line[] Axis { get; set; } = new Line[2];
//Used to draw the grid.
public GridLine DrawGrid(int max_value, int scale_factor, Canvas canvas) //Draws the grid
{
int x = 0;
int y = 0;
while (x < max_value) // Used to draw lines from the center out to the far right.
{
YGridline.Add(new Line() {
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 2,
X1 = x,
Y1 = -max_value,
X2 = x,
Y2 = max_value
});
canvas.Children.Add(YGridline[YGridline.Count - 1]);
x += scale_factor;
}
x = 0;
y = 0;
while (x > -max_value) //used to draw lines from the center to the far left.
{
YGridline.Add(new Line() {StrokeThickness = 2,
Stroke = new SolidColorBrush(Colors.Black),
X1 = x ,
Y1 = -max_value,
X2 = x,
Y2 = max_value
});
canvas.Children.Add(YGridline[YGridline.Count - 1]);
x -= scale_factor;
}
y = 0;
x = 0;
while (y < max_value) //used to draw lines from the center to the bottom
{
XGridline.Add(new Line() {
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 2,
X1 = -max_value,
Y1 = y,
X2 = max_value,
Y2 = y
});
canvas.Children.Add(XGridline[XGridline.Count - 1]);
y += scale_factor;
}
y = 0;
x = 0;
while (y > -max_value) //Used to draw lines from the center to the top.
{
XGridline.Add(new Line() {
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 2,
X1 = -max_value,
Y1 = y,
X2 = max_value,
Y2 = y
});
canvas.Children.Add(XGridline[XGridline.Count - 1]);
y -= scale_factor;
}
//VERTICLE LINE- Y Axis
Axis[0] = (new Line() { Stroke = new SolidColorBrush(Colors.Black), StrokeThickness = 3, X1 = 0, Y1 = -max_value, X2 = 0, Y2 = max_value });
canvas.Children.Add(Axis[0]);
//Horizontal line - X Axis
Axis[1] = (new Line() { Stroke = new SolidColorBrush(Colors.Black), StrokeThickness = 3, X1 = -max_value, Y1 = 0, X2 = max_value, Y2 = 0 });
canvas.Children.Add(Axis[1]);
return this;
}
}
编辑: 如果您只想拥有渐变背景,为什么不将矩形设置为不具有透明填充,然后在其后设置渐变背景呢?我仍然建议您查看我的代码,因为根据您以后打算对网格进行的操作,您可能会发现实用地生成网格更加容易。