node_with_size.dart 2.06 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
part of flutter_sprites;
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

/// The super class of any [Node] that has a size.
///
/// NodeWithSize adds the ability for a node to have a size and a pivot point.
class NodeWithSize extends Node {

  /// Changing the size will affect the size of the rendering of the node.
  ///
  ///     myNode.size = new Size(1024.0, 1024.0);
  Size size;

  /// The normalized point which the node is transformed around.
  ///
  ///     // Position myNode from is middle top
  ///     myNode.pivot = new Point(0.5, 0.0);
  Point pivot;

  /// Creates a new NodeWithSize.
  ///
  /// The default [size] is zero and the default [pivot] point is the origin. Subclasses may change the default values.
  ///
  ///     var myNodeWithSize = new NodeWithSize(new Size(1024.0, 1024.0));
Hixie's avatar
Hixie committed
28 29 30
  NodeWithSize(this.size) {
    if (size == null)
      size = Size.zero;
31
    pivot = Point.origin;
32 33 34 35 36 37 38 39
  }

  /// Call this method in your [paint] method if you want the origin of your drawing to be the top left corner of the
  /// node's bounding box.
  ///
  /// If you use this method you will need to save and restore your canvas at the beginning and
  /// end of your [paint] method.
  ///
Adam Barth's avatar
Adam Barth committed
40
  ///     void paint(Canvas canvas) {
41 42 43 44 45 46 47
  ///       canvas.save();
  ///       applyTransformForPivot(canvas);
  ///
  ///       // Do painting here
  ///
  ///       canvas.restore();
  ///     }
Adam Barth's avatar
Adam Barth committed
48
  void applyTransformForPivot(Canvas canvas) {
49 50 51 52 53 54 55
    if (pivot.x != 0 || pivot.y != 0) {
      double pivotInPointsX = size.width * pivot.x;
      double pivotInPointsY = size.height * pivot.y;
      canvas.translate(-pivotInPointsX, -pivotInPointsY);
    }
  }

56
  @override
57 58 59 60 61 62 63 64 65 66
  bool isPointInside (Point nodePoint) {

    double minX = -size.width * pivot.x;
    double minY = -size.height * pivot.y;
    double maxX = minX + size.width;
    double maxY = minY + size.height;
    return (nodePoint.x >= minX && nodePoint.x < maxX &&
            nodePoint.y >= minY && nodePoint.y < maxY);
  }
}