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