提问人:Xamarin 提问时间:11/17/2023 更新时间:11/18/2023 访问量:39
如何在 xamarin 中的多边形内添加标签
How to add a label inside polygon in xamarin
问:
我有一个 xamarin 应用程序想要在多边形内添加标签。标注位置应垂直居中,水平从多边形开始。如何实现这一点。有没有其他替代方法可以创建此 UI.Is 可以创建如下所示的 Stacklayout。
这是我当前的代码和输出
<Grid Grid.Row="3">
<Polygon Points="50 0, 0 100, 800 100, 800 0"
Fill="{StaticResource PrimaryGray}"
HorizontalOptions="EndAndExpand"
VerticalOptions="FillAndExpand">
</Polygon>
<Label Text="To sdfghuiop retyuiop sdftyguiop sertdyfuio sdtfyguio"
HorizontalOptions="Center"
HorizontalTextAlignment="Start"
VerticalOptions="Center"/>
</Grid>
答:
0赞
Liqun Shen-MSFT
11/17/2023
#1
我更喜欢使用 SkiaSharp。
让我们使用 SkiaSharp 做一个小演示。首先,可以安装 SkiaSharp.Views.Forms NuGet。
这是 xaml,我们将 SKCanvasView 放入网格中。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
...
xmlns:skia="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms">
.....
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<skia:SKCanvasView Grid.Row="1" PaintSurface="SKCanvasView_PaintSurface" />
</Grid>
这是背后的代码,
void SKCanvasView_PaintSurface(System.Object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
{
SKImageInfo info = e.Info;
SKSurface surface = e.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
//Draw the polygon
SKPath path = new SKPath();
path.MoveTo(0.2f * info.Width, 0.1f * info.Height);
path.LineTo(0.9f * info.Width, 0.1f * info.Height);
path.LineTo(0.9f * info.Width, 0.9f * info.Height);
path.LineTo(0.1f * info.Width, 0.9f * info.Height);
path.Close();
SKPaint fillPaint = new SKPaint
{
Style = SKPaintStyle.Fill,
Color = SKColors.Gray
};
//Draw the text
string str = "To sdfghuiop retyuiop sdftyguiop sertdyfuio sdtfyguio";
SKPaint textPaint = new SKPaint
{
Color = SKColors.Black
};
// Adjust TextSize property so text is 50% of screen width
float textWidth = textPaint.MeasureText(str);
textPaint.TextSize = 0.5f * info.Width * textPaint.TextSize / textWidth;
// Find the text bounds
SKRect textBounds = new SKRect();
textPaint.MeasureText(str, ref textBounds);
float xText = info.Width / 2 - textBounds.MidX;
float yText = info.Height / 2 - textBounds.MidY;
// draw the polygon and text on the canvas
canvas.DrawPath(path, fillPaint);
canvas.DrawText(str, xText, yText, textPaint);
}
相关文档,
绘制多边形:集成文本和图形
绘制文本:SkiaSharp 中的路径基础知识
您可以参考上述文档,并根据您的需求对代码进行一些调整。
这是效果,
评论