JGe*_*geJ 4 c# xamarin maui .net-6.0
我对 c# 和 maui 还很陌生。我想了解如何在画布上绘图。我阅读了文档并在网上找到了一些东西。我想画简单的线条。

我所做的是在里面创建了类MauiProgram.cs
namespace TestMauiX;
using Microsoft.Maui.Graphics;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
return builder.Build();
}
}
public class MyFirstDrawing : IDrawable
{
public void Draw(ICanvas canvas, RectangleF dirtyRect)
{
canvas.StrokeColor = Colors.Red;
canvas.StrokeSize = 6;
canvas.DrawLine(10, 10, 90, 100);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有了MainPage.xaml,但是我应该如何把那张图放进去呢?
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestMauiX.MainPage"
BackgroundColor="{DynamicResource SecondaryColor}">
<ScrollView>
<Grid RowSpacing="25" RowDefinitions="Auto,Auto,Auto,Auto,*"
Padding="{OnPlatform iOS='30,60,30,30', Default='30'}">
<Label
Text="Hello, World!"
Grid.Row="0"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center" />
....
Run Code Online (Sandbox Code Playgroud)
Pix*_*tor 11
目前,对于预览 MAUI 应用程序,您可以使用GraphicsView控件进行绘图,就像在控件上一样Canvas。
一个例子:
using Microsoft.Maui.Graphics;
public class MyFirstDrawing : IDrawable
{
public void Draw(ICanvas canvas, RectangleF dirtyRect)
{
canvas.StrokeColor = Colors.Red;
canvas.StrokeSize = 6;
canvas.DrawLine(10, 10, 90, 100);
}
}
Run Code Online (Sandbox Code Playgroud)
ContentPage添加对您的可绘制类的引用ContentPage.Resources。然后GraphicsView向页面布局添加一个控件,并将Drawable属性设置为使用标记扩展部分Key中为可绘制对象设置的值。ContentPage.ResourcesStaticResource<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:drawable="clr-namespace:YOUR_APP_NAMESPACE"
...>
<ContentPage.Resources>
<drawable:MyFirstDrawing x:Key="MyDrawable" />
</ContentPage.Resources>
<ScrollView>
<Grid RowSpacing="20"
RowDefinitions="Auto,*"
Padding="{OnPlatform iOS='30,60,30,30', Default='30'}">
<Label
Text="Hello, World!"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center"
Grid.Row="0"/>
<GraphicsView
x:Name="Canvas"
HorizontalOptions="Fill"
Drawable="{StaticResource MyDrawable}"
HeightRequest="100"
Grid.Row="1"/>
</Grid>
</ScrollView>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)