我正在尝试使用Xamarin.Android中的GridLayout创建一个棋盘。 GridLayout中的每个视图都是描绘一块的图像视图(如果正方形包含一块)。在添加图像资源之前,电路板显示正常。但是一旦添加了图像,它就会将ImageView的大小推得比预期的大得多。
这是我正在使用的代码。对于棋盘上的每个方块运行以下方法并创建ImageView并将其返回以添加到GridLayout:
public View BuildSquare(Square squareModel)
{
SquareView rtn = new SquareView(this.Activity, squareModel); //SquareView extends ImageView
rtn.UpdateBackgroundColor(); //set square color
if (squareModel.Piece != null)
{
rtn.DrawPiece();
}
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
//set weight of each row and column to ensure equal size
param.RowSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
param.ColumnSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
rtn.LayoutParameters = param;
return rtn;
}
和DrawPiece()方法如下,它设置图像资源:
public void DrawPiece()
{
if (squareModel.Piece == null) return;
string key = squareModel.Piece.GetPieceNotation();
int resource = -1;
//get the image resource corresponding to the piece on the ssquare
if (AndroidConstants.PieceResources.TryGetValue(key, out resource))
{
this.SetImageResource(resource);
}
this.SetScaleType(ScaleType.FitXy);
}
当我注释掉rtn.DrawPiece()行时,电路板会正确显示,如下所示:
但是,当包含该行并设置了图像资源时,它显示如下:
你在这里看到的是板上左上方的大幅度充气以容纳图像。我希望缩放图像以适合上面第一张图片中的方块。我尝试过不同的ScaleTypes,但似乎没什么区别。这与使用GridLayout有关吗?或者是否还有其他事情发生在我身上?
答案 0 :(得分:1)
我认为您需要将高度和宽度设置为SquareView
。
例如:
public View BuildSquare(Square squareModel)
{
SquareView rtn = new SquareView(this, squareModel); //SquareView extends ImageView
rtn.UpdateBackgroundColor(); //set square color
if (squareModel.Piece ==0)
{
rtn.DrawPiece();
}
//Set the height and width
GridLayout.LayoutParams param = new GridLayout.LayoutParams(new ViewGroup.LayoutParams(50, 50));
//set weight of each row and column to ensure equal size
param.RowSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
param.ColumnSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
rtn.LayoutParameters = param;
return rtn;
}
结果: