2013-06-03 38 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