2017-04-11 250 views
1

enter image description here如何設置按鈕的大小Xamarin

左側標籤代碼

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。 但按鈕大小與設置大小不同。 上面的圖像的兩個按鈕是相同的大小。 左邊是帶背景色的標籤,右邊是按鈕。 但大小不一樣。

我想讓按鈕的大小正確。

+1

我很抱歉,但我對你正在嘗試做的完全喪失。您正在討論標題中的索引,問題中的大小,以及完成時談論如何避免四捨五入。請限制每個帖子的一個問題,並試圖清楚你想要達到的目標,你嘗試過的以及失敗的地方。 –

+0

我編輯問題只設置按鈕大小。抱歉。 –

回答

1

如果最有可能收縮按鈕,則表示網格佈局。您可以在下面找到一個工作示例。你一定要記住,使用字體大小的硬編碼值可能會導致文本不適合按鈕。我在代碼中使用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; } 

我的頁面。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); 
    } 

結束結果

隨着字號= 14

Correctly sized button and label

隨着字號= 16

Font too large for button