我有一個顯示圓的小程序,當您單擊該圓時,它會再次出現在屏幕上的其他位置。繪製隨機放置的圓有時會變成橢圓
這在90%的情況下效果很好,但有時候這個圈子是越野車。可能是它出現在視圖外部,顯示爲橢圓形而不是圓形,或者位於視圖外部的中間位置。
任何人都可以指向正確的方向,我做錯了什麼?
屏幕:
代碼示例:
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);
}
}
請詳細說明。爲什麼2失敗?寬度和高度都是33,並給出了高度爲10的示例1,看起來是正確的。在3中,x和y,從1和2的視圖的表觀大小看起來也是正確的。你的問題到底是什麼? – Simon