You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将.NET Maui中GraphicsView的宽高设为窗口或屏幕大小?

解决GraphicsView占满窗口/屏幕的问题

问题原因

你直接赋值Width和Height报错是因为这两个是控件的只读属性,代表控件实际渲染后的尺寸,不能手动修改。要设置期望尺寸,需要用WidthRequest和HeightRequest,同时还要配合布局选项确保控件能填充可用空间。

方案1:纯XAML实现(推荐)

如果要让GraphicsView占满父容器的所有可用空间,最简单的方式是调整布局选项和容器:

方式A:修改VerticalStackLayout及子元素的布局选项

<VerticalStackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
    <GraphicsView x:Name="modelerArea"
                  Drawable="{StaticResource drawable}"
                  HorizontalOptions="FillAndExpand"
                  VerticalOptions="FillAndExpand" />
</VerticalStackLayout>
  • 给VerticalStackLayout设置FillAndExpand,让它先占满窗口空间
  • 给GraphicsView同样设置FillAndExpand,让它填充整个VerticalStackLayout

方式B:改用Grid作为根容器

Grid默认会让子元素填充自身所有空间,写法更简洁:

<Grid>
    <GraphicsView x:Name="modelerArea"
                  Drawable="{StaticResource drawable}" />
</Grid>

方案2:后台代码动态设置

如果需要基于屏幕/窗口尺寸动态设置,注意要转换为逻辑像素(MAUI使用逻辑像素而非物理像素),并且修改WidthRequest/HeightRequest:

// 获取屏幕信息并转换为逻辑像素
var displayInfo = DeviceDisplay.MainDisplayInfo;
double logicalWidth = displayInfo.Width / displayInfo.Density;
double logicalHeight = displayInfo.Height / displayInfo.Density;

// 设置请求尺寸
modelerArea.WidthRequest = logicalWidth;
modelerArea.HeightRequest = logicalHeight;

// 确保控件填充空间
modelerArea.HorizontalOptions = LayoutOptions.Fill;
modelerArea.VerticalOptions = LayoutOptions.Fill;

如果是要适配窗口大小(而非整个屏幕,比如桌面端窗口),可以获取窗口尺寸:

if (Application.Current?.MainWindow != null)
{
    modelerArea.WidthRequest = Application.Current.MainWindow.Width;
    modelerArea.HeightRequest = Application.Current.MainWindow.Height;
    modelerArea.HorizontalOptions = LayoutOptions.Fill;
    modelerArea.VerticalOptions = LayoutOptions.Fill;
}

内容的提问来源于stack exchange,提问作者JJJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:20:49