如何在xamarin中的多边形内添加标签

问题描述 投票:0回答:1

我有一个xamarin应用程序想要在多边形内添加标签。标签位置应该垂直居中并水平从多边形开始。如何实现这一目标。是否有其他替代方法来创建此 UI。是否可以创建如下所示的 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>

第一张图片是纵向视图,第二张是横向视图

c# xamarin layout xamarin.ios
1个回答
0
投票

我更喜欢使用SkiaSharp

让我们使用 SkiaSharp 制作一个小演示。首先,您可以安装 SkiaSharp.Views.Forms NuGet。

这是xaml,我们将SKCanvasView放入Grid中。

<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 中的路径基础知识

您可以参考上述文档,根据您的需求对您的代码进行一些调整。

希望有帮助。

这是效果,

肖像

风景

© www.soinside.com 2019 - 2024. All rights reserved.