custom_render_box.dart 1.67 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

8 9
class RenderDots extends RenderConstrainedBox {
  RenderDots() : super(additionalConstraints: const BoxConstraints.expand());
10 11

  // Makes this render box hittable so that we'll get pointer events.
12
  @override
13
  bool hitTestSelf(Offset position) => true;
14

15
  final Map<int, Offset> _dots = <int, Offset>{};
16

17
  @override
18 19 20 21 22 23 24 25 26 27
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    if (event is PointerDownEvent || event is PointerMoveEvent) {
      _dots[event.pointer] = event.position;
      markNeedsPaint();
    } else if (event is PointerUpEvent || event is PointerCancelEvent) {
      _dots.remove(event.pointer);
      markNeedsPaint();
    }
  }

28
  @override
29 30
  void paint(PaintingContext context, Offset offset) {
    final Canvas canvas = context.canvas;
31
    canvas.drawRect(offset & size, Paint()..color = const Color(0xFF0000FF));
32

33
    final Paint paint = Paint()..color = const Color(0xFF00FF00);
34
    for (final Offset point in _dots.values)
35
      canvas.drawCircle(point, 50.0, paint);
36 37

    super.paint(context, offset);
38 39 40
  }
}

41
class Dots extends SingleChildRenderObjectWidget {
42
  const Dots({ Key? key, Widget? child }) : super(key: key, child: child);
43 44

  @override
45
  RenderDots createRenderObject(BuildContext context) => RenderDots();
46 47 48
}

void main() {
Ian Hickson's avatar
Ian Hickson committed
49 50 51
  runApp(
    const Directionality(
      textDirection: TextDirection.ltr,
52 53 54
      child: Dots(
        child: Center(
          child: Text('Touch me!'),
Ian Hickson's avatar
Ian Hickson committed
55 56 57 58
        ),
      ),
    ),
  );
59
}