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

Flutter Paint Canvas:实现线条侧边而非端点间渐变的方法

实现Flutter画布线条侧边渐变效果

要实现线条的侧边渐变(即渐变方向垂直于线条本身),核心是让线性渐变的方向与线条方向垂直,而非沿着线条长度方向。具体实现步骤如下:

关键逻辑

  1. 计算线条的方向向量,推导其垂直方向的单位向量
  2. 根据线条的strokeWidth,确定渐变的起止偏移点(覆盖线条两侧边缘)
  3. 将垂直方向的偏移点作为线性渐变的起止坐标

完整代码示例

import 'dart:ui' as ui;

// 定义线条的两个端点
final startPoint = Offset(50, 50);
final endPoint = Offset(250, 150);
final strokeWidth = 4.0;

// 计算线条方向向量
final lineDirection = endPoint - startPoint;
// 生成垂直于线条的单位向量(顺时针方向,若要反向可改为Offset(lineDirection.dy, -lineDirection.dx))
final perpendicularDir = Offset(-lineDirection.dy, lineDirection.dx).normalized;

// 计算渐变的起止点:从线条一侧边缘到另一侧边缘
final gradientStart = startPoint + perpendicularDir * (strokeWidth / 2);
final gradientEnd = startPoint - perpendicularDir * (strokeWidth / 2);

canvas.drawLine(
  startPoint,
  endPoint,
  Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = strokeWidth
    ..shader = ui.Gradient.linear(
      gradientStart,
      gradientEnd,
      [Colors.blue, Colors.red], // 替换为你需要的渐变颜色
    ),
);

代码说明

  • lineDirection:获取线条从起点到终点的方向向量
  • perpendicularDir:通过对方向向量做旋转变换,得到垂直于线条的单位向量,保证渐变方向与线条侧边平行
  • gradientStart和gradientEnd:基于线条起点向垂直方向偏移strokeWidth/2,正好覆盖线条的整个宽度范围,确保渐变完全填充线条侧边

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:55:24