2013-06-03 40 views
0

我有一个显示圆的小程序,当您单击该圆时,它会再次出现在屏幕上的其他位置。绘制随机放置的圆有时会变成椭圆

这在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); 
    } 
} 
+0

请详细说明。为什么2失败?宽度和高度都是33,并给出了高度为10的示例1,看起来是正确的。在3中,x和y,从1和2的视图的表观大小看起来也是正确的。你的问题到底是什么? – Simon

回答

2

假设你r.Next方法是否正常工作,我认为这个问题是在这里:

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

您正在分别设置左侧,顶部,右侧,底部的边距,我不认为您要设置右侧和底部边距。您可能想尝试使用setX和setY方法。

+0

是的,谢谢。这是问题的一部分。它解决了它在视图之外的部分。但它并没有解决它被视为椭圆形的部分。但那是因为我没有考虑标题和状态栏高度。现在它可以工作。 – Martin