将动态生成的项目放在按钮周围的圆圈中
本文关键字:周围 按钮 动态 项目 | 更新日期: 2023-09-27 18:15:48
我正在创建一个silverlight应用程序,我必须动态创建按钮。但我需要把它们放在一个圆圈周围的按钮,我点击生成其他按钮(图中,按钮应该在黑线周围的'test project'按钮)
我不知道每次会生成多少个按钮,但我知道每个按钮的大小是静态的。我不太确定该怎么做。目前我的按钮创建如下
foreach (Item a in itemList)
{
Button newButton = new Button();
newButton.Height = 50;
newButton.Width = 50;
newButton.Content = a.getName();
newButton.Click += new RoutedEventHandler(addedClick);
newButton.HorizontalAlignment = HorizontalAlignment.Left;
newButton.VerticalAlignment = VerticalAlignment.Top;
newButton.Margin = new Thickness(0, 0, 0, 0);
newButton.Style = (Style)Application.Current.Resources["RB"];
buttons.Add(newButton);
}
我最大的问题是我不太确定如何得到"测试项目"按钮的中心点。
编辑:好的,现在我已经为每个按钮设置了一组坐标,我该如何放置它们呢?我不知道怎么用画布。我试图设置一个,但它一直表现得像一个stackpanel(没有。setleft/。settop)。你的意思是像圆方程:
Double distanceFromCenter = 5;
Double angleInDegrees = 90;
Double angleAsRadians = (angleInDegrees* Math.PI) / 180.0;
Double centerX = 100;
Double centerY = 100;
Double x = centerX + Math.Cos(angleAsRadians) * distanceFromCenter;
Double y = centerY + Math.Sin(angleAsRadians) * distanceFromCenter;
给出的点距离(centerX, center)
为distanceFromCenter
个单位,angle
为90度。注意,这只适用于弧度,所以我们必须转换为弧度。
var radius = 100;
var angle = 360 / itmeList.Count * Math.PI / 180.0f;
var center = new Point(100, 100);
for (int i = 0; i < itemList.Count; i++)
{
var x = center.X + Math.Cos(angle * i) * radius;
var y = center.Y + Math.Sin(angle * i) * radius;
Button newButton = new Button();
newButton.RenderTransformOrigin = new Point(x, y);
newButton.Height = 50;
newButton.Width = 50;
newButton.Content = a.getName();
newButton.Click += new RoutedEventHandler(addedClick);
newButton.HorizontalAlignment = HorizontalAlignment.Left;
newButton.VerticalAlignment = VerticalAlignment.Top;
newButton.Margin = new Thickness(0, 0, 0, 0);
newButton.Style = (Style)Application.Current.Resources["RB"];
buttons.Add(newButton);
}
假设您希望您的按钮在圆圈上均匀间隔,您应该首先生成您希望它们的角度列表。例如
double eachSection = 2 * Math.PI / count;
var anglesInRadians = Enumerable.Range(0, count).Select(x => x * eachSection);
然后使用这个公式找到每个角度的x/y坐标,并使用Canvas
或其他东西来定位这些位置的按钮
public static Point PointOnCircle(double radius, double angleInRadians, Point origin)
{
double x = radius * Math.Cos(angleInRadians) + origin.X;
double y = radius * Math.Sin(angleInRadians) + origin.Y;
return new Point(x, y);
}