随机放置圆圈的绘制有时会变成椭圆形

时间:2013-06-03 19:56:45

标签: android xamarin.android xamarin-studio

我有一个显示圆圈的小程序,当您点击该圆圈时,它会重新出现在屏幕上的其他位置。

这在90%的案例中表现良好,但有时候圈子是错误的。可能是它出现在视图外部,显示为椭圆形而不是圆形,或者位于视图的中间。

任何人都可以指出我正确的方向,我做错了什么?

屏幕:

enter image description here enter image description here enter image description here

代码示例:

public class Activity1 : Activity
{
    int margin = 20;

    Button ball;
    TextView debug;
    RelativeLayout mRel;
    RelativeLayout.LayoutParams ballParams;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Create a debug label
        debug = new TextView(this);

        // Create a new ball
        ball = new Button(this);
        ball.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.round_button));
        ball.Click += (o, e) => {
             RandomizePosition();
        };

        // Set ball parameters
        ballParams = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WrapContent,
        RelativeLayout.LayoutParams.WrapContent);

        // Create relative layout
        mRel = new RelativeLayout(this);
        mRel.SetBackgroundColor(Color.AntiqueWhite);
        mRel.AddView(ball);
        mRel.AddView(debug);
        SetContentView(mRel);

        // Randmize the ball position
        RandomizePosition ();
    }

    void RandomizePosition ()
    {
        // Get height and width
        Display display = WindowManager.DefaultDisplay;
        int width = display.Width;
        int height = display.Height;
        int relativeBallSize = ((((width * 2) + (height * 2)) / 100) * 3);

        // Set random parameters
        Random r = new Random();
        int maxWidth = (width - relativeBallSize);
        int maxHeight = (height - relativeBallSize);
        int x = r.Next(margin, (maxWidth < margin) ? margin : maxWidth);
        int y = r.Next(margin, (maxHeight < margin) ? margin : maxHeight);

        // Place the ball randomly
        ballParams.SetMargins(x, y, x, y);
        ball.LayoutParameters = ballParams;
        ball.SetHeight(relativeBallSize);
        ball.SetWidth(relativeBallSize);

        debug.SetText(string.Format("X = {0}, Y = {1}, Width = {2}, Height = {3}, Ball Width = {4}, Ball Height = {5}, Ball size = {6}", x, y, width, height, ball.Width, ball.Height, relativeBallSize), TextView.BufferType.Normal);
    }
}

1 个答案:

答案 0 :(得分:2)

假设您的r.Next方法工作正常,我认为问题在于:

ballParams.SetMargins(x, y, x, y);

您分别设置左,上,右,下的边距,我认为您不想设置右边距和下边距。您可能希望尝试使用setX和setY方法。