以下代码将帮助根据手机屏幕的高度和宽度设计手机屏幕。
基于此的设计将适合所有移动分辨率。
PCL:
App.cs
public class App : Application
{
public static int screenHeight, screenWidth;
public App()
{
MainPage = new UserLogin();
//The root page of your application
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
Xamarin.Android:
MainActivity.cs
#region 屏幕高度和宽度
var pixels = Resources.DisplayMetrics.WidthPixels;
var scale = Resources.DisplayMetrics.Density;
var dps = (double)((pixels - 0.5f) / scale);
var ScreenWidth = (int)dps;
App.screenWidth = ScreenWidth;
//RequestedOrientation = ScreenOrientation.Portrait;
pixels = Resources.DisplayMetrics.HeightPixels;
dps = (double)((pixels - 0.5f) / scale);
var ScreenHeight = (int)dps;
App.screenHeight = ScreenHeight;
结束区域
Xamarin.iOS
AppDelegate.cs
#region For Screen Height & Width
App.screenWidth = (int)UIScreen.MainScreen.Bounds.Width;
App.screenHeight = (int)UIScreen.MainScreen.Bounds.Height;
#endregion
PCL:
如果您使用 MVVM 模式,您必须在 ViewModel 中获取这些 ScreenHeight 和 ScreenWidth 然后为您的视图和布局提供高度和宽度。
// The below two lines will use to get the MOBILE SCREEN HEIGHT && WIDTH in ViewModel
int heightScreen=App.screenHeight;
int widthScreen=App.screenHeigh;
XAML 设计:
UserLogin.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:local="clr-
SreenSizeDemo;assembly=SreenSizeDemo" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SreenSizeDemo.UserLogin">
<StackLayout>
<Label x:Name="lblTitle" HorizontalOptions="FillAndExpand"/>
<Image x:Name="imgProfile" Source="Logo.png" />
<StackLayout>
<ContentPage>
UserLogin.xaml.cs
public partial class UserLogin : BaseContentPage
{
// Here you get the MOBILE SCREEN HEIGHT && WIDTH
int heightScreen=App.screenHeight;
int widthScreen=App.screenHeight;
public UserLogin()
{
lblTitle.FontSize=height=Screen/36.8;
//The above value is equal to fontsize =20
imgProfile.HeightRequest=heightScreeen/10;
imgProfile. WidthRequest=heightScreeen/10;
}
}
C# 设计:
public class UserLogin: ContentPage
{
// Here you get the MOBILE SCREEN HEIGHT && WIDTH
int heightScreen=App.screenHeight;
int widthScreen=App.screenHeight;
public UserLogin()
{
Label lab = new Label()
{
FontSize = heightScreen/ 36.8
//the above value is equal to fontsize =20
};
Image imgProfile=new Image()
{
Source="Logo.png",
HeightRequest=heightScreeen/10,
WidthRequest=heightScreeen/10
}
}
}