我想在Xamarin Forms项目中将图像缩小50%。我似乎无法找到一个明确的答案我如何解决这个问题。我发现了一篇关于Xamarin.Labs的古老博客文章,但不确定这是否仍然相关。
选项1 是尝试让每个孩子在stacklayout中占50%
var horizontalLayout = new StackLayout ();
horizontalLayout.Orientation = StackOrientation.Horizontal;
//What do I add here?
//add views to the view hierarchy
horizontalLayout.Children.Add (Photo ());
horizontalLayout.Children.Add (textLayout);
选项2 使图片宽度为50%
private Image Photo ()
{
var image = new Image ();
image.WidthRequest = ??;
image.SetBinding (Image.SourceProperty, "Member.MemberPhoto");
return image;
}
textLayout
也是图像右侧的堆栈布局
StackLayout textLayout = new StackLayout ();
textLayout.Children.Add (CompanyName ());
textLayout.Children.Add (SubCategory ());
textLayout.Children.Add (Address ());
答案 0 :(得分:4)
使用Grid
作为外部容器,并使用ColumnDefinition
1和GridLength
GridUnitType
指定Star
,如下所示: -
Grid objGrid = new Grid()
{
VerticalOptions = LayoutOptions.StartAndExpand
};
objGrid.ColumnDefinitions.Add(new ColumnDefinition
{
Width = new GridLength(1, GridUnitType.Star)
});
objGrid.ColumnDefinitions.Add(new ColumnDefinition
{
Width = new GridLength(1, GridUnitType.Star)
});
下面显示的是一个Button
的完整示例,点击后会显示图片大小明确设置为各种值。
无论图像尺寸是小还是大于50%宽度区域,都会使Grid
的布局保持在50%
宽度。
示例: - 强>
StackLayout objStackLayout = new StackLayout();
Grid objGrid = new Grid()
{
VerticalOptions = LayoutOptions.StartAndExpand
};
objGrid.ColumnDefinitions.Add(new ColumnDefinition
{
Width = new GridLength(1, GridUnitType.Star)
});
objGrid.ColumnDefinitions.Add(new ColumnDefinition
{
Width = new GridLength(1, GridUnitType.Star)
});
objStackLayout.Children.Add(objGrid);
Image objImage = new Image()
{
Source = ImageSource.FromFile(" {put some image here} "),
VerticalOptions = LayoutOptions.Start
};
objGrid.Children.Add(objImage, 0,0);
Label objLabel = new Label();
objLabel.Text = "Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... Some long text goes here.... blah blah blah..... ";
objGrid.Children.Add(objLabel, 1,0);
Button objButton = new Button();
objButton.Text = "Change Image Width" ;
objButton.Clicked+=((o2,e2)=>
{
if (objImage.WidthRequest == -1)
{
objImage.WidthRequest = 50;
}
else if (objImage.WidthRequest == 50)
{
objImage.WidthRequest = 150;
}
else if (objImage.WidthRequest == 150)
{
objImage.WidthRequest = 350;
}
else if (objImage.WidthRequest == 350)
{
objImage.WidthRequest = 50;
}
});
objStackLayout.Children.Add(objButton);