画出一定距离的n个椭圆

时间:2015-09-07 19:28:44

标签: c# wpf shapes

我想在C#中完成一些事情:

enter image description here

为此我正在考虑

#define           clrSignalLABEL       clrAqua                  // LITERAL-way
#define           iLabelFontSIZE       24

string            signalTextFONT       'Times New Roman';       // STRING-way

我使用15作为椭圆(宽度和高度)的大小,然后对于每个椭圆,我将它增加1.4倍。

代码是:

1. get center of canvas
2. draw center ellipse using center
3. taking the center ellipse, do two loops, one to draw ellipses that are above center, and other loop to draw ellipses that are under center
(I assigned same `x` to all and changed `y` to set ellipses positions)
4. Everytime a cicle passed, update size (incrise it) and `Y` multiplying it by size and its indes in loop

然而,我得到了未对齐且距离很差的椭圆 enter image description here

如何改进代码或循环以获得正确的结果?

2 个答案:

答案 0 :(得分:1)

你正在通过不使用数据绑定来改变自己的方式。只需创建一个视图模型来保存椭圆数据:

public class TestViewModel
{
    public IList<object> Items { get; private set; }

    public TestViewModel()
    {
        this.Items = new List<object>();
        for (int i = 0; i <= 12; i++)
        {
            var size = 5.0 * Math.Pow(1.4, Math.Abs(i-6));
            this.Items.Add(new { X = 50 + i * 25 - size / 2, Y = 50 + i * 25 - size / 2, Radius = size });
        }
    }
}

代码方面,您已经为视图绑定创建了足够的数据。您正在渲染项目列表,因此请创建ItemsControl。您想在Canvas上绘制,因此将其设置为ItemsPanel。您希望每个元素都是一个椭圆,因此将其设置为ItemTemplate。最后将样式属性设置为定位和调整每个元素的大小:

    <ItemsControl ItemsSource="{Binding Items}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Ellipse Fill="Red"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="{x:Type ContentPresenter}">
                <Setter Property="Canvas.Left" Value="{Binding X}" />
                <Setter Property="Canvas.Top" Value="{Binding Y}" />
                <Setter Property="Width" Value="{Binding Radius}" />
                <Setter Property="Height" Value="{Binding Radius}" />
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>

结果:

enter image description here

答案 1 :(得分:0)

首先,当您重置大小变量时,需要将其重置为20而不是15.接下来,当您偏移圆时,您需要将x坐标与y坐标相同。边缘与画布表现得很有趣。我使用了一个Grid,它运行正常。我认为重要的是你意识到x坐标也必须被偏移。