简体   繁体   English

如何为容器创建渐变边框

[英]How to create a gradient border for a container

I'm trying to replicate the following behavior:我正在尝试复制以下行为:

在此处输入图像描述

Specifically the gradient on the border.特别是边框上的渐变。 I can easily copy this behavior by using two Containers stacked on each other: one that holds the radial-gradient (for the border) and another on top which is the background color.我可以通过使用两个相互堆叠的Containers轻松复制此行为:一个包含径向渐变(用于边框),另一个在顶部是背景颜色。 However, that doesn't work for me as I want the background color to be partially transparent so the content below this card is somewhat visible.但是,这对我不起作用,因为我希望背景颜色部分透明,因此这张卡片下方的内容有些可见。

How else would you approach this?你还会如何处理这个问题? Use some sort of custom paint?使用某种定制油漆? Last case scenario I can just import the png and use it as a background but wanted to make this in code.最后一种情况,我可以只导入 png 并将其用作背景,但想在代码中制作它。

PS: You can create the following gradient by using a RadialGradient where the center is the same as the rectangle's center. PS:您可以使用中心与矩形中心相同的RadialGradient创建以下渐变。

So I managed to do this by simply using a CustomPainter to create the border.所以我设法通过简单地使用CustomPainter创建边框来做到这一点。 Turns out it's pretty straightforward.事实证明这很简单。 Thanks to @esentis for helping out!感谢@esentis 的帮助!

final gradient = RadialGradient(
  colors: [
    ThemeColors.BLUE,
    Colors.white.withAlphaPercent(0),
  ],
  radius: 1,
  center: Alignment.center,
);

final start = Offset(size.width * 0, size.height * 0);
final end = Offset(size.width * 1, size.height * 1);
final center = Offset(size.width * 0.5, size.height * 0.5);

final rect = Rect.fromPoints(start, end);
final rRect = RRect.fromRectAndRadius(rect, Radius.circular(12));
final paint = Paint()
  ..strokeWidth = 6
  ..style = PaintingStyle.stroke
  ..shader = gradient.createShader(Rect.fromCircle(
    center: center,
    radius: size.width * 0.5,
  ));

canvas.drawRRect(rRect, paint);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM