首页 > 解决方案 > 如何在 Flutter 中以编程方式更改 Rive/Flare 中渐变填充的开始/结束位置?

问题描述

我有一个简单的球,它使用渐变填充使其看起来像是从一侧点亮:

球

我想在运行时在 Flutter 中修改渐变填充(例如,让它看起来像灯光相对于球移动)。我能够找到这样的坐标:

final fill = (artboard.getNode("Ellipse") as FlutterActorShape).fill as FlutterRadialFill;
print(fill.renderStart);
print(fill.renderEnd);

但是,我找不到修改这些值的方法。我尝试使用Vec2D覆盖这些值,但是它不会改变渲染(可能是因为从这些需要无效的值计算了一些东西?):

Vec2D.copy(
          _fill.renderStart,
          Vec2D.fromValues(
              200 - _component.x, 200 - _component.y));

标签: flutterdartrive

解决方案


这个属性没有一个很好的有用的设置器(关键帧操纵它并使内部状态无效),但是有一点额外的冗长(我们真的应该让这个更友好)代码你可以做到:


class MutateGradient extends FlareController {
  // Store the fill so you don't need to look it up each frame.
  FlutterRadialFill _radialFill;

  // I chose to drive the end position of the gradient with a sin wave so i use
  // a field to accumulate the phase.
  double _phase = 0;

  @override
  bool advance(FlutterActorArtboard artboard, double elapsed) {
    if (_radialFill == null) {
      // Didn't find the fill during init, early out with a false meaning we're
      // done.
      return false;
    }

    _phase += elapsed;

    // No nice setter on the end so we have to set the values manually and then
    // mark the paint dirty so the update loop updates the actual paint and
    // points used to render. Note that the position here can be either in the
    // path's local transform or world (artboard) transform depending on whether
    // transformAffectsStroke was selected in Rive.
    Vec2D.copy(
        _radialFill.end, Vec2D.fromValues(-100, 100 + sin(_phase*2) * 50));
    _radialFill.markPaintDirty();

    // Return true to get another call the next frame...
    return true;
  }

  @override
  void initialize(FlutterActorArtboard artboard) {
    // Find the fill we want to manipulate.
    var node = artboard.getNode("Ellipse");
    if (node is FlutterActorShape) {
      var fill = node.fill;
      if (fill is FlutterRadialFill) {
        _radialFill = fill;
      }
    }
  }

  @override
  void setViewTransform(Mat2D viewTransform) {
    // Inentionally empty, we don't need to convert from artboard (world) to
    // view space in this example.
  }
}

发送仇恨邮件至 luigi@rive.app 或随意公开羞辱我@luigirosso <3


推荐阅读