如何在Xamarin中以编程方式创建不规则按钮?

时间:2013-09-05 16:56:43

标签: ios c#-4.0 xamarin.ios

我正在尝试以编程方式为我的应用程序中的交互元素创建按钮。界面看起来像圆环图,如果用户触摸圆环图中的一个区域,它将突出显示该区域和所有其他区域。我现在不太关心颜色,我试图让七个按钮出现。以下是我尝试创建按钮的代码示例:

var radius = (Frame.Width - 38) / 2.0f;
var innerRadius = radius - 32;
var diameter = radius * 2;

energyCircleView = new UIView();
energyCircleView.BackgroundColor = UIColor.White;
energyCircleView.Frame = new RectangleF(19, confirmEntryButton.Frame.Top - 16 - (diameter), diameter, diameter);
energyCircleView.Layer.CornerRadius = radius;
energyCircleView.Layer.MasksToBounds = true;

var center = new PointF(energyCircleView.Frame.X + radius, energyCircleView.Frame.Y + radius);
var ninety = MathHelper.TwoPi * (90.0f / 360.0f);
var seventh = MathHelper.TwoPi * (1.0f / 7.0f) * 360.0f;

for (int i = 0; i < 7; i++)
{
    var startAngle = ninety + (i * seventh);
    var endAngle = ninety + ((i + 1) * seventh);

    var shapePath = new CGPath();
    shapePath.AddArc(center.X, center.Y, radius, startAngle, endAngle, false);
    shapePath.AddArc(center.X, center.Y, innerRadius, endAngle, startAngle, true);

    var shapeLayer = new CAShapeLayer();
    shapeLayer.Path = shapePath;

    var button = new UIButton();
    button.Frame = new RectangleF(0, 0, diameter, diameter);
    button.BackgroundColor = MyColors[i];
    button.Layer.Mask = shapeLayer;
    button.Layer.MasksToBounds = true;

    energyButtons.Add(button);
}

foreach (UIButton button in energyButtons)
{
    energyCircleView.AddSubview(button);
}

1 个答案:

答案 0 :(得分:1)

您正在添加按钮作为视图的子视图。但是你不会自己展示视图。

添加以下代码以显示energyCircleView:

this.View.AddSubview(energyCircleView);