gpt4 book ai didi

button - 如何设置按钮的大小Xamarin

转载 作者:行者123 更新时间:2023-12-01 12:22:09 25 4
gpt4 key购买 nike

enter image description here

左标签代码

xaml

<Label x:Name="presentBtn" Text="선물함" FontSize="16" HorizontalOptions="Start"  HorizontalTextAlignment="Center" VerticalTextAlignment="Center" Grid.Column="0" BackgroundColor="#A8D2F1">

c#

presentBtn.HeightRequest = 45.0 * (double)App.ScreenWidth / 720.0;
presentBtn.WidthRequest = 150.0* (double)App.ScreenWidth / 720.0;

...

右键代码

xaml

<Button x:Name="ticketBtn" Text="티켓충전" HorizontalOptions="End"  FontSize="16" Clicked="changeTicketCharge" Grid.Column="1" VerticalOptions="CenterAndExpand" BorderRadius="0"/>

c#

ticketBtn.HeightRequest = 45* (double)App.ScreenWidth / 720.0;
ticketBtn.WidthRequest = 150* (double)App.ScreenWidth / 720.0;

我在 xamarin.form 中制作按钮并设置 HeightRequest、WidthRequest。但按钮大小与设置大小不同。上图的两个按钮大小相同。左边是带有背景颜色的标签,右边是按钮。但大小不一样。

我想让按钮的大小正确。

最佳答案

您的网格布局很可能会限制按钮。您可以在下面找到一个工作示例。您需要记住,对字体大小使用硬编码值可能会导致文本不适合按钮。我从代码中的 16 开始,但文本被剪掉了,因为字体对于按钮来说太大了。您也可以创建一个简单的计算来获得合适的字体大小。由你决定。

MainActivity.cs

 protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);

SetScreenWidthAndHeight();
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}

App.xaml.cs

  public static int DisplayWidth { get; set; }
public static int DisplayHeight { get; set; }

MyPage.cs

 private Button _testBtn;
private Label _testLbl;
public HomePage()
{
var height = 45 * App.DisplayHeight / 720;
var width = 150 * App.DisplayWidth / 720;

_testLbl = new Label { FontSize = 16, Text = "testing", HeightRequest = height, WidthRequest = width };
_testBtn = new Button { FontSize = 16, Text = "testing", HeightRequest = height, WidthRequest = width};
var a = new Grid
{
ColumnDefinitions = { new ColumnDefinition { Width = GridLength.Auto } },
RowDefinitions = { new RowDefinition { Height = GridLength.Auto } }
};
a.Children.Add(_testBtn, 0, 0);
a.Children.Add(_testLbl, 0, 1);
_mainContent = new StackLayout { Children = { a } };

Content = _mainContent;
}

像素到 DP

private int ConvertPixelsToDp(float pixelValue)
{
var dp = (int)((pixelValue) / Resources.DisplayMetrics.Density);
return dp;
}

屏幕宽高计算

private void SetScreenWidthAndHeight()
{
var metrics = Resources.DisplayMetrics;

App.DisplayWidth = ConvertPixelsToDp(metrics.WidthPixels);
App.DisplayHeight = ConvertPixelsToDp(metrics.HeightPixels);
}

最终结果

FontSize=14

Correctly sized button and label

FontSize=16

Font too large for button

关于button - 如何设置按钮的大小Xamarin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com