【MAUI】圆角实现方式总结-示例代码(仅限 Android)

  1. 创建自定义控件
using Microsoft.Maui.Controls;

namespace YourApp
{
    public class CustomRoundedButton : Button
    {
        public static readonly BindableProperty CornerRadiusProperty = BindableProperty.Create(
            nameof(CornerRadius),
            typeof(double),
            typeof(CustomRoundedButton),
            default(double));

        public double CornerRadius
        {
            get => (double)GetValue(CornerRadiusProperty);
            set => SetValue(CornerRadiusProperty, value);
        }
    }
}
  1. 创建自定义渲染器
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Compatibility;
using Microsoft.Maui.Controls.Compatibility.Platform.Android;
using Microsoft.Maui.Controls.Platform;
using Android.Content;
using Android.Graphics.Drawables;
using Android.Views;
using Android.Widget;

[assembly: ExportRenderer(typeof(YourApp.CustomRoundedButton), typeof(YourApp.Droid.CustomRoundedButtonRenderer))]

namespace YourApp.Droid
{
    public class CustomRoundedButtonRenderer : ButtonRenderer
    {
        public CustomRoundedButtonRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            if (Control != null && Element is CustomRoundedButton customButton)
            {
                Control.Background = GetRoundedBackground(customButton.CornerRadius);
            }
        }

        private Drawable GetRoundedBackground(double cornerRadius)
        {
            var radius = (int)cornerRadius;
            var color = ContextCompat.GetColor(Context, Resource.Color.button_background_color);

            var shape = new GradientDrawable();
            shape.SetShape(GradientDrawable.Rectangle);
            shape.SetColor(color);
            shape.SetCornerRadius(radius);

            return shape;
        }
    }
}

方法五:使用 XAML 样式

你可以在 XAML 中定义样式来统一设置控件的圆角。

上一篇:Unity性能优化1【基础篇】


下一篇:flask 接口还在执行中,前端接收到接口请求超时,解决方案