对于颜色我们可以使用Color.withOpacity,但是对于渐变不存在这种方法。将不透明度应用于现有渐变上的每种颜色的最简单方法是什么?这可能吗?
我尝试实现自定义扩展,Gradient但这个想法似乎不起作用,因为我不知道它是什么梯度,所以目前我必须为每种类型的梯度实现扩展。
extension LinearGradientExtension on LinearGradient {
/// Applies [opacity] to all colors in gradient and returns a new [LinearGradient]
LinearGradient withOpacity(double opacity) {
return LinearGradient(
colors: _applyOpacity(colors, opacity),
begin: begin,
end: end,
stops: stops,
tileMode: tileMode,
transform: transform,
);
}
}
extension RadialGradientExtension on RadialGradient {
/// Applies [opacity] to all colors in gradient and returns a new [RadialGradient]
RadialGradient withOpacity(double opacity) {
/// ...
}
}
List<Color> _applyOpacity(List<Color> colors, double opacity) {
return colors
.map((Color color) => color.withOpacity(color.opacity * opacity))
.toList()
;
}
Run Code Online (Sandbox Code Playgroud)
我不想Opacity为此使用任何小部件(例如)。
小智 5
颜色参数需要一个颜色列表,因此您基本上可以在该列表中放置任何具有任何不透明度的颜色小部件。
对于线性渐变,我使用了这个实现,希望这就是您正在寻找的
Container(
foregroundDecoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Colors.black,
Colors.black.withOpacity(0.8),
Colors.black.withOpacity(0.5),
Colors.black.withOpacity(0),
],
),
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3876 次 |
| 最近记录: |