flutter开发实战-css的linear-gradient的值转换成LinearGradient

flutter开发实战-css的linear-gradient的值转换成LinearGradient

在开发中遇到了参照前端的css的属性值,需要将css的linear-gradient值转换成LinearGradient,这样可以直接设置相应的值。这里暂时不涉及到,颜色值名称、color-stop1,后续把包含color-stop1用于指定渐变的起止颜色的属性转换、正则表达式转换等也相应的整理一下。这里的颜色为#ffffff格式的。

下面将linear-gradient(179deg,#eab6ea,#978bfb)转换成flutter的LinearGradient类对象。

我们先了解一下css的linear-gradient

一、css之linear-gradient

linear-gradient() 函数用于创建一个表示两种或多种颜色线性渐变的图片。
创建一个线性渐变,需要指定两种颜色,还可以实现不同方向(指定为一个角度)的渐变效果,如果不指定方向,默认从上到下渐变。

/* 从上到下,蓝色渐变到红色 */
linear-gradient(blue, red);
 
/* 渐变轴为45度,从蓝色渐变到红色 */
linear-gradient(45deg, blue, red);
 
/* 从右下到左上、从蓝色渐变到红色 */
linear-gradient(to left top, blue, red);
 
/* 从下到上,从蓝色开始渐变、到高度40%位置是绿色渐变开始、最后以红色结束 */
linear-gradient(0deg, blue, green 40%, red);

background-image: linear-gradient(direction, color-stop1, color-stop2, …);

direction:用角度值指定渐变的方向(或角度)。
color-stop1, color-stop2,…:用于指定渐变的起止颜色。

linear-gradient(179deg,#eab6ea,#978bfb)
css效果图

在这里插入图片描述

二、flutter之LinearGradient

LinearGradient一个用于创建线性渐变颜色装饰,它能够根据给定的起点和终点,在这个线性渐变的方向上,使用给定的颜色进行过渡,所以LinearGradient实现的过渡是平滑的。

针对于linear-gradient(179deg,#eab6ea,#978bfb)转换成flutter的LinearGradient

如果css的linear-gradient存在角度需要将flutter的LinearGradient中begin设置成Alignment.bottomCenter,end设置为Alignment.topCenter;

// 和css角度,方向保持一致
Alignment  begin = Alignment.bottomCenter;
Alignment  end = Alignment.topCenter;

之后通过计算一下角度设置transform。

GradientRotation? transform;
  // 角度
  // 计算角度
  double degree = 179;
  double p = 180.0;
  double radians = (math.pi / p) * degree;
  transform = GradientRotation(radians);

完成代码代码如下

LinearGradient linearGradient(BuildContext context) {
    
    
  Alignment begin = Alignment.centerLeft;
  Alignment end = Alignment.centerRight;
  GradientRotation? transform;
  // 角度
  // 计算角度
  double degree = 179;
  double p = 180.0;
  double radians = (math.pi / p) * degree;
  transform = GradientRotation(radians);

  // 和css角度,方向保持一致
  begin = Alignment.bottomCenter;
  end = Alignment.topCenter;

  LinearGradient linearGradient = LinearGradient(
    colors: [
      ColorUtil.hexColor(0xeab6ea),
      ColorUtil.hexColor(0x978bfb),
    ],
    begin: begin,
    end: end,
    transform: transform,
  );

  return linearGradient;
}

转换成flutter的linearGradient效果图

在这里插入图片描述

三、小结

flutter开发实战-css的linear-gradient的值转换成LinearGradient。将css的linear-gradient值转换成LinearGradient,可以方便参考页面的检查中css元素设置改成LinearGradient使用的属性值。这里暂时不涉及到,颜色值名称、color-stop1,后续把包含color-stop1用于指定渐变的起止颜色的属性转换、正则表达式转换等也相应的整理一下。

学习记录,每天不停进步。

猜你喜欢

转载自blog.csdn.net/gloryFlow/article/details/131713101