stock_arrow.dart 2.5 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 stocks;
6

7 8 9 10 11 12 13 14 15 16 17
class StockArrowPainter extends CustomPainter {
  StockArrowPainter({ this.color, this.percentChange });

  final Color color;
  final double percentChange;

  void paint(PaintingCanvas canvas, Size size) {
    Paint paint = new Paint()..color = color;
    paint.strokeWidth = 1.0;
    const double padding = 2.0;
    assert(padding > paint.strokeWidth / 2.0); // make sure the circle remains inside the box
18
    double r = (size.shortestSide - padding) / 2.0; // radius of the circle
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    double centerX = padding + r;
    double centerY = padding + r;

    // Draw the arrow.
    double w = 8.0;
    double h = 5.0;
    double arrowY;
    if (percentChange < 0.0) {
      h = -h;
      arrowY = centerX + 1.0;
    } else {
      arrowY = centerX - 1.0;
    }
    Path path = new Path();
    path.moveTo(centerX, arrowY - h); // top of the arrow
    path.lineTo(centerX + w, arrowY + h);
    path.lineTo(centerX - w, arrowY + h);
    path.close();
    paint.style = ui.PaintingStyle.fill;
    canvas.drawPath(path, paint);

    // Draw a circle that circumscribes the arrow.
    paint.style = ui.PaintingStyle.stroke;
    canvas.drawCircle(new Point(centerX, centerY), r, paint);
  }

  bool shouldRepaint(StockArrowPainter oldPainter) {
    return oldPainter.color != color
        || oldPainter.percentChange != percentChange;
  }
}

51
class StockArrow extends StatelessComponent {
52
  StockArrow({ Key key, this.percentChange }) : super(key: key);
53 54 55 56 57 58 59 60 61 62 63

  final double percentChange;

  int _colorIndexForPercentChange(double percentChange) {
    double maxPercent = 10.0;
    double normalizedPercentChange = math.min(percentChange.abs(), maxPercent) / maxPercent;
    return 100 + (normalizedPercentChange * 8.0).floor() * 100;
  }

  Color _colorForPercentChange(double percentChange) {
    if (percentChange > 0)
64 65
      return Colors.green[_colorIndexForPercentChange(percentChange)];
    return Colors.red[_colorIndexForPercentChange(percentChange)];
66 67
  }

68
  Widget build(BuildContext context) {
69
    return new Container(
70 71 72 73 74 75 76 77 78 79
      width: 40.0,
      height: 40.0,
      margin: const EdgeDims.symmetric(horizontal: 5.0),
      child: new CustomPaint(
        painter: new StockArrowPainter(
          // TODO(jackson): This should change colors with the theme
          color: _colorForPercentChange(percentChange),
          percentChange: percentChange
        )
      )
80 81 82
    );
  }
}