Tus*_*tel 19 width xamarin xamarin.forms
我正在创建一个Xamarin Forms项目,我根据不同的设备找不到当前的屏幕宽度.
我知道如何在android和ios中完成它,但需要一种方法来在便携式中找到宽度.
Par*_*tel 41
你可以尝试这个Application.Current.MainPage.Width在我的情况下这工作,我能够在便携式项目本身找到设备宽度.
Nic*_*ert 27
常用代码(在App.xaml.cs中)
public static int ScreenHeight {get; set;}
public static int ScreenWidth {get; set;}
Run Code Online (Sandbox Code Playgroud)
Android部分(在MainActivity.cs中,在OnCreate方法中)
App.ScreenHeight = (int) (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
App.ScreenWidth = (int) (Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);
Run Code Online (Sandbox Code Playgroud)
iOS部分(在AppDelegate.cs中,在FinishedLaunching方法中)
App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
Run Code Online (Sandbox Code Playgroud)
因此App.ScreenHeight和App.ScreenWidth将在App启动时初始化,然后您就可以在公共代码中的任何位置使用它们.
EvZ*_*EvZ 20
我知道这是一个旧线程,但值得一提的是,最近Xamarin.Essentials NuGet pakage已经发布,并且有一个有用的类DeviceDisplay应该为你处理这个任务.
文档可以在这里找到.
用法示例:
// Get Metrics
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
// Orientation (Landscape, Portrait, Square, Unknown)
var orientation = mainDisplayInfo.Orientation;
// Rotation (0, 90, 180, 270)
var rotation = mainDisplayInfo.Rotation;
// Width (in pixels)
var width = mainDisplayInfo.Width;
// Height (in pixels)
var height = mainDisplayInfo.Height;
// Screen density
var density = mainDisplayInfo.Density;
Run Code Online (Sandbox Code Playgroud)
小智 6
当您在ContentPage中时,可以使用Width属性.例如,
protected override void OnAppearing()
{
base.OnAppearing();
double w = this.Width;
}
Run Code Online (Sandbox Code Playgroud)
请注意,这是在布局阶段设置的.因此,您只能在页面初始化后使用它,否则它是-1.
https://developer.xamarin.com/api/property/Xamarin.Forms.VisualElement.Width/
我想在共享代码中创建一个静态结构,这样我就可以轻松访问屏幕宽度/高度值(以及在 xAML 中进行绑定)。
应用程序命名空间中的结构(例如在 App.xaml.cs 中):
using System;
using Xamarin.Forms;
namespace YourAppName {
...
public struct Constant {
public static double ScreenWidth = Application.Current.MainPage.Width;
public static double ScreenHeight = Application.Current.MainPage.Height;
}
}
Run Code Online (Sandbox Code Playgroud)
在 C# 中检索屏幕宽度:
var labelWidth = Constant.ScreenHeight * 0.2;
// then do something with labelWidth
Run Code Online (Sandbox Code Playgroud)
在 XAML 中检索屏幕宽度:
<Label Text="Text with insane font size" FontSize="{Binding Source={x:Static local:Constant.ScreenWidth}}"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36487 次 |
| 最近记录: |