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

MAUI/C#中Border对角着色——矩形对角线垂线交点计算问题

解决矩形Border对角着色的渐变起止点计算问题

你需要的是让LinearGradientBrush的50%分界线精准对齐矩形对角线,核心是找到垂直于该对角线且与矩形边框相交的两个点作为渐变起止点,以下是具体实现方案:

数学推导(相对坐标下)

以WPF相对坐标系统为例(矩形左上角为(0,0),右下角为(1,1)),设矩形宽高比 r = 实际宽度 / 实际高度:

  • 宽矩形(r > 1):起止点分别在左侧边和右侧边上,坐标为 (0, (r-1)/(2r)) 和 (1, (r+1)/(2r))
  • 高矩形(r < 1):起止点分别在顶部边和底部边上,坐标为 ((1-r)/2, 0) 和 ((1+r)/2, 1)
  • 正方形(r = 1):回到你原本的方案 (0,1) 和 (1,0)

代码实现

直接根据Border的实际尺寸计算起止点,适配所有矩形场景:

// 假设目标Border控件名为targetBorder
double width = targetBorder.ActualWidth;
double height = targetBorder.ActualHeight;
Point startPoint, endPoint;

// 避免控件未加载时的零值异常
if (width <= 0 || height <= 0)
{
    startPoint = new Point(0, 1);
    endPoint = new Point(1, 0);
}
else
{
    double ratio = width / height;
    if (ratio > 1)
    {
        startPoint = new Point(0, (ratio - 1) / (2 * ratio));
        endPoint = new Point(1, (ratio + 1) / (2 * ratio));
    }
    else if (ratio < 1)
    {
        startPoint = new Point((1 - ratio) / 2, 0);
        endPoint = new Point((1 + ratio) / 2, 1);
    }
    else
    {
        startPoint = new Point(0, 1);
        endPoint = new Point(1, 0);
    }
}

// 应用渐变Brush
targetBorder.Background = new LinearGradientBrush(
    new GradientStopCollection()
    {
        new GradientStop(Colors.Blue, 0.5f),
        new GradientStop(Colors.Red, 0.5f)
    },
    startPoint,
    endPoint);

原理说明

通过宽高比计算的起止点,确保渐变的中间分界(50%位置)正好是矩形的对角线,同时渐变方向垂直于该对角线,完美实现你需要的对角着色效果,无论矩形是宽型还是高型都能精准适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:33:34