在Flutter中如何在画布上画一个Widget?

问题描述 投票:2回答:1

有没有什么方法可以画出一个 Widget 在某一位置 Canvas?

更具体的说,我想把子部件的 Marker的关系 FlutterMap 另行 Canvas 当真 FlutterMap 小部件。这里是一个尝试创建一个 CustomPainter 可以做到这一点,但我不知道如何在画布上实际绘制小组件。在画布上使用 RenderObject 需要 PaintingContext我不知道如何检索。

class MarkerPainter extends CustomPainter {
  MapController mc;
  BuildContext context;
  List<Marker> markers;

  MarkerPainter(this.context, this.mc, this.markers);

  @override
  void paint(Canvas canvas, Size size) {
    if( markers != null && markers.isNotEmpty ){
      for(int i=0; i<markers.length; i++){
        Marker marker = markers[i];
        Offset o = myCalculateOffsetFromLatLng(marker.point, mc, context);

        // Won't work, this needs a PaintingContext...
        marker.builder(context).createElement().renderObject.paint(context, o); 
      }
    }
  }

  @override
  bool shouldRepaint(MarkerPainter oldDelegate) => oldDelegate.markers != markers;
}
flutter flutter-layout flutter-widget flutter-canvas fluttermap
1个回答
0
投票

你不能做到这一点与一个 自定义画家.

这个类只是真正的简化。RenderObject,它可以访问所有与画家相关的内容(以及布局+更多)。

你应该做的是,代替 自定义画家,创建一个 RenderBox (a 2d RenderObject)

在您的情况下,您想要的是绘制一个小组件的列表。在这种情况下,您将需要创建:

最后,这样使用的widget。

MyExample(
  children: [
    Text('foo'),
    Text('bar'),
  ],
),

会被这样写。

import 'package:flutter/rendering.dart';
import 'package:flutter/material.dart';

class MyExample extends MultiChildRenderObjectWidget {
  MyExample({
    Key key,
    @required List<Widget> children,
  }) : super(key: key, children: children);

  @override
  RenderMyExample createRenderObject(BuildContext context) {
    return RenderMyExample();
  }
}

class MyExampleParentData extends ContainerBoxParentData<RenderBox> {}

class RenderMyExample extends RenderBox
    with ContainerRenderObjectMixin<RenderBox, MyExampleParentData> {
  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! MyExampleParentData) {
      child.parentData = MyExampleParentData();
    }
  }

  @override
  void performLayout() {
    size = constraints.biggest;

    for (var child = firstChild; child != null; child = childAfter(child)) {
      child.layout(
        // limit children to a max height of 50
        constraints.copyWith(maxHeight: 50),
      );
    }
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    // Paints all children in order vertically, separated by 50px

    var verticalOffset = .0;
    for (var child = firstChild; child != null; child = childAfter(child)) {
      context.paintChild(child, offset + Offset(0, verticalOffset));

      verticalOffset += 50;
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.