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

Flutter中如何为LinearGradient配置transform属性?

在Flutter中为LinearGradient设置transform属性的方法

嘿,我来帮你搞定LinearGradient的transform属性设置!在Flutter里,LinearGradient的transform属性需要接收一个**GradientTransform**类型的对象,Flutter内置了几个常用的实现类,下面我给你逐个举例说明,直接套进你的代码里就能用~

常用的GradientTransform实现类

1. GradientRotation(旋转渐变)

这个可以让渐变围绕中心点旋转指定角度,参数是弧度值(比如π/2就是90度)。示例代码:

// 需要先导入dart:math包
import 'dart:math';

// ...

decoration: BoxDecoration(
  gradient: LinearGradient(
    colors: [Colors.black, Colors.white],
    begin: Alignment.topCenter,
    end: Alignment.bottomCenter,
    // 旋转90度(π/2弧度)
    transform: const GradientRotation(math.pi / 2),
  ),
)

2. GradientScale(缩放渐变)

可以对渐变进行缩放,参数是x和y方向的缩放比例,还能指定缩放的中心点:

decoration: BoxDecoration(
  gradient: LinearGradient(
    colors: [Colors.black, Colors.white],
    begin: Alignment.topCenter,
    end: Alignment.bottomCenter,
    // x方向缩放2倍,y方向保持1倍,中心点在容器中心
    transform: const GradientScale(scaleX: 2.0, scaleY: 1.0, center: Alignment.center),
  ),
)

3. GradientTranslate(平移渐变)

可以把渐变在x或y方向上平移,参数是基于容器尺寸的相对偏移量:

decoration: BoxDecoration(
  gradient: LinearGradient(
    colors: [Colors.black, Colors.white],
    begin: Alignment.topCenter,
    end: Alignment.bottomCenter,
    // x方向平移0.2倍容器宽度,y方向平移0.1倍容器高度
    transform: const GradientTranslate(offset: Offset(0.2, 0.1)),
  ),
)

4. 组合多个变换

如果需要同时应用多种变换,可以用Matrix4构建自定义变换矩阵,通过GradientTransform的匿名实现来组合:

import 'dart:math';
import 'package:flutter/src/painting/matrix_utils.dart';

// ...

decoration: BoxDecoration(
  gradient: LinearGradient(
    colors: [Colors.black, Colors.white],
    begin: Alignment.topCenter,
    end: Alignment.bottomCenter,
    transform: GradientTransform((bounds) {
      // 先旋转45度,再整体缩放1.5倍
      final rotationMatrix = Matrix4.rotationZ(math.pi / 4);
      final scaleMatrix = Matrix4.diagonal3Values(1.5, 1.5, 1.0);
      return MatrixUtils.multiplyTransforms([rotationMatrix, scaleMatrix]);
    }),
  ),
)

快速替换你的代码

你只需要把原代码里的???替换成上面任意一种GradientTransform实例就行,比如用旋转效果的话:

decoration: BoxDecoration(
  gradient: LinearGradient(
    colors: [Colors.black, Colors.white],
    begin: Alignment.topCenter,
    end: Alignment.bottomCenter,
    transform: const GradientRotation(math.pi / 2),
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:52:42