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

如何实现.NET MAUI Label控件内文本字符单独旋转?

.NET MAUI 实现Label文本旋转但控件不旋转

要实现仅旋转Label内的文本而非控件本身,有两种常用方案,分别适配不同场景:

方案一:使用SkiaSharp绘制旋转文本(跨平台简洁方案)

通过SkiaSharp直接在画布上绘制旋转后的文本,无需针对不同平台编写渲染逻辑,是最省心的跨平台方案。

步骤:

  1. 安装NuGet包 SkiaSharp.Views.Maui。
  2. 在XAML中添加SKCanvasView控件:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:skia="clr-namespace:SkiaSharp.Views.Maui;assembly=SkiaSharp.Views.Maui"
             x:Class="YourApp.MainPage">
    <skia:SKCanvasView x:Name="RotatedTextCanvas" PaintSurface="OnCanvasPaintSurface" />
</ContentPage>
  1. 在代码后台处理PaintSurface事件,绘制旋转文本:
private void OnCanvasPaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
    var canvas = e.Surface.Canvas;
    canvas.Clear();

    // 配置文本样式
    var text = "需要旋转的文本内容";
    var textPaint = new SKPaint
    {
        Color = SKColors.Black,
        TextSize = 24,
        IsAntialias = true,
        TextAlign = SKTextAlign.Center
    };

    // 获取文本尺寸,用于居中计算
    var textBounds = new SKRect();
    textPaint.MeasureText(text, ref textBounds);

    // 设置旋转中心为画布中心,旋转角度可自定义(示例为90度)
    var centerX = e.Info.Width / 2f;
    var centerY = e.Info.Height / 2f;
    canvas.Save();
    canvas.RotateDegrees(90, centerX, centerY);
    // 绘制文本,调整Y轴偏移让文本垂直居中
    canvas.DrawText(text, centerX, centerY - textBounds.Top / 2, textPaint);
    canvas.Restore();
}

方案二:自定义Label+平台渲染器(贴近原生控件方案)

如果需要保留Label的原有属性(如字体、颜色绑定等),可以通过自定义Label控件搭配各平台渲染器实现。

步骤:

  1. 创建自定义Label控件,添加旋转角度绑定属性:
public class RotatedTextLabel : Label
{
    public static readonly BindableProperty RotationAngleProperty =
        BindableProperty.Create(
            nameof(RotationAngle), 
            typeof(double), 
            typeof(RotatedTextLabel), 
            defaultValue: 0.0);

    public double RotationAngle
    {
        get => (double)GetValue(RotationAngleProperty);
        set => SetValue(RotationAngleProperty, value);
    }
}
  1. 编写Android平台渲染器:
[assembly: ExportRenderer(typeof(RotatedTextLabel), typeof(RotatedTextLabelRenderer))]
namespace YourApp.Platforms.Android
{
    public class RotatedTextLabelRenderer : LabelRenderer
    {
        public RotatedTextLabelRenderer(Context context) : base(context) { }

        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            if (Control != null && e.NewElement is RotatedTextLabel)
            {
                Control.SetWillNotDraw(false);
                Control.Paint += OnControlPaint;
            }
        }

        private void OnControlPaint(object sender, Android.Graphics.PaintEventArgs e)
        {
            if (Element is not RotatedTextLabel rotatedLabel) return;
            var textView = (TextView)sender;
            var text = textView.Text;
            if (string.IsNullOrEmpty(text)) return;

            var paint = e.Paint;
            var textBounds = new Android.Graphics.Rect();
            paint.TextSize = textView.TextSize;
            paint.GetTextBounds(text, 0, text.Length, textBounds);

            // 保存画布状态,旋转后恢复
            e.Canvas.Save();
            var centerX = textView.Width / 2f;
            var centerY = textView.Height / 2f;
            e.Canvas.Rotate((float)rotatedLabel.RotationAngle, centerX, centerY);
            // 绘制居中文本
            var drawX = centerX - textBounds.Width() / 2f;
            var drawY = centerY + textBounds.Height() / 2f;
            e.Canvas.DrawText(text, drawX, drawY, paint);
            e.Canvas.Restore();
            e.Handled = true; // 禁止原生绘制,避免重复
        }

        protected override void Dispose(bool disposing)
        {
            if (Control != null) Control.Paint -= OnControlPaint;
            base.Dispose(disposing);
        }
    }
}
  1. 编写iOS平台渲染器:
[assembly: ExportRenderer(typeof(RotatedTextLabel), typeof(RotatedTextLabelRenderer))]
namespace YourApp.Platforms.iOS
{
    public class RotatedTextLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            if (Control != null) Control.BackgroundColor = UIColor.Clear;
        }

        public override void DrawText(CGRect rect)
        {
            if (Element is not RotatedTextLabel rotatedLabel)
            {
                base.DrawText(rect);
                return;
            }

            var context = UIGraphics.GetCurrentContext();
            context.SaveState();

            // 旋转画布(角度转弧度)
            var center = new CGPoint(rect.GetMidX(), rect.GetMidY());
            context.TranslateCTM(center.X, center.Y);
            context.RotateCTM((nfloat)(rotatedLabel.RotationAngle * Math.PI / 180));
            context.TranslateCTM(-center.X, -center.Y);

            // 调整文本位置保持居中
            var textSize = Control.AttributedText.Size;
            var centeredRect = new CGRect(
                rect.X + (rect.Width - textSize.Width)/2,
                rect.Y + (rect.Height - textSize.Height)/2,
                textSize.Width,
                textSize.Height
            );

            base.DrawText(centeredRect);
            context.RestoreState();
        }
    }
}
  1. 在XAML中使用自定义控件:
<local:RotatedTextLabel Text="旋转文本示例" RotationAngle="90" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:58:20