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

Flutter中RadialGradient缩放位置偏移:是否需平移及计算方法?

解决RadialGradient缩放后位置偏移的问题

是的,必须通过平移修正水平位置——因为Matrix4的scale默认是围绕坐标系原点(也就是容器的左上角)进行缩放的,水平缩放后,渐变的中心会被拉向一侧,导致整体位置偏移。

平移距离的计算方法

假设水平缩放倍数为scaleX(比如你用的1.5),容器的宽度为bounds.width:

  1. 原渐变中心的水平位置是容器宽度的一半:bounds.width / 2
  2. 缩放后,这个中心位置会被拉伸到:(bounds.width / 2) * scaleX
  3. 要让中心回到原来的位置,需要向左平移的距离为:-(scaleX - 1) * bounds.width / 2

修改后的代码示例

BoxDecoration(
  gradient: RadialGradient(
    // 可根据需求添加渐变参数,比如colors、radius等
    colors: [Colors.deepPurple, Colors.transparent],
    transform: MyTransform(1.5),
  ),
)

class MyTransform extends GradientTransform {
  final double scaleX;

  MyTransform(this.scaleX);

  @override
  Matrix4 transform(Rect bounds, {TextDirection? textDirection}) {
    final width = bounds.width;
    // 计算水平平移量
    final translateX = -(scaleX - 1) * width / 2;
    return Matrix4.identity()
      // 先平移再缩放(顺序不能搞反)
      ..translate(translateX, 0.0)
      ..scale(scaleX, 1.0, 1.0);
  }
}

注意:如果你的RadialGradient设置了自定义center(不是默认的Alignment.center),需要结合center的偏移量调整平移计算,但默认中心场景下上面的代码完全适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:12:34