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

5

6 7
import 'dart:math' as math;
import 'dart:typed_data';
8
import 'dart:ui' as ui show Gradient, TextBox, lerpDouble;
9

10
import 'package:flutter/foundation.dart';
11

12
import 'alignment.dart';
13
import 'basic_types.dart';
14
import 'box_fit.dart';
15
import 'colors.dart';
16
import 'decoration.dart';
17
import 'edge_insets.dart';
18
import 'image_provider.dart';
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
import 'text_painter.dart';
import 'text_span.dart';
import 'text_style.dart';

/// Possible ways to draw Flutter's logo.
enum FlutterLogoStyle {
  /// Show only Flutter's logo, not the "Flutter" label.
  ///
  /// This is the default behavior for [FlutterLogoDecoration] objects.
  markOnly,

  /// Show Flutter's logo on the left, and the "Flutter" label to its right.
  horizontal,

  /// Show Flutter's logo above the "Flutter" label.
  stacked,
}

/// An immutable description of how to paint Flutter's logo.
class FlutterLogoDecoration extends Decoration {
  /// Creates a decoration that knows how to paint Flutter's logo.
  ///
41 42
  /// The [style] controls whether and where to draw the "Flutter" label. If one
  /// is shown, the [textColor] controls the color of the label.
43
  ///
44
  /// The [textColor], [style], and [margin] arguments must not be null.
45
  const FlutterLogoDecoration({
46
    this.textColor = const Color(0xFF757575),
47 48
    this.style = FlutterLogoStyle.markOnly,
    this.margin = EdgeInsets.zero,
49
  }) : assert(textColor != null),
50 51
       assert(style != null),
       assert(margin != null),
52
       _position = identical(style, FlutterLogoStyle.markOnly) ? 0.0 : identical(style, FlutterLogoStyle.horizontal) ? 1.0 : -1.0,
53 54
       _opacity = 1.0;

55
  const FlutterLogoDecoration._(this.textColor, this.style, this.margin, this._position, this._opacity);
56

57
  /// The color used to paint the "Flutter" text on the logo, if [style] is
58 59 60 61
  /// [FlutterLogoStyle.horizontal] or [FlutterLogoStyle.stacked].
  ///
  /// If possible, the default (a medium grey) should be used against a white
  /// background.
62 63
  final Color textColor;

64 65 66 67 68 69
  /// Whether and where to draw the "Flutter" text. By default, only the logo
  /// itself is drawn.
  // This property isn't actually used when painting. It's only really used to
  // set the internal _position property.
  final FlutterLogoStyle style;

70 71 72
  /// How far to inset the logo from the edge of the container.
  final EdgeInsets margin;

73 74 75 76 77 78 79 80
  // The following are set when lerping, to represent states that can't be
  // represented by the constructor.
  final double _position; // -1.0 for stacked, 1.0 for horizontal, 0.0 for no logo
  final double _opacity; // 0.0 .. 1.0

  bool get _inTransition => _opacity != 1.0 || (_position != -1.0 && _position != 0.0 && _position != 1.0);

  @override
81
  bool debugAssertIsValid() {
82
    assert(textColor != null
83
        && style != null
84
        && margin != null
85 86 87 88
        && _position != null
        && _position.isFinite
        && _opacity != null
        && _opacity >= 0.0
89
        && _opacity <= 1.0);
90 91 92 93 94 95 96 97 98 99
    return true;
  }

  @override
  bool get isComplex => !_inTransition;

  /// Linearly interpolate between two Flutter logo descriptions.
  ///
  /// Interpolates both the color and the style in a continuous fashion.
  ///
100 101
  /// If both values are null, this returns null. Otherwise, it returns a
  /// non-null value. If one of the values is null, then the result is obtained
102
  /// by scaling the other value's opacity and [margin].
103
  ///
104
  /// {@macro dart.ui.shadow.lerp}
105 106 107 108
  ///
  /// See also:
  ///
  ///  * [Decoration.lerp], which interpolates between arbitrary decorations.
109
  static FlutterLogoDecoration? lerp(FlutterLogoDecoration? a, FlutterLogoDecoration? b, double t) {
110
    assert(t != null);
111 112
    assert(a == null || a.debugAssertIsValid());
    assert(b == null || b.debugAssertIsValid());
113 114 115
    if (a == null && b == null)
      return null;
    if (a == null) {
116
      return FlutterLogoDecoration._(
117
        b!.textColor,
118
        b.style,
119
        b.margin * t,
120 121 122 123 124
        b._position,
        b._opacity * t.clamp(0.0, 1.0),
      );
    }
    if (b == null) {
125
      return FlutterLogoDecoration._(
126
        a.textColor,
127
        a.style,
128
        a.margin * t,
129 130 131 132
        a._position,
        a._opacity * (1.0 - t).clamp(0.0, 1.0),
      );
    }
133 134 135 136
    if (t == 0.0)
      return a;
    if (t == 1.0)
      return b;
137
    return FlutterLogoDecoration._(
138
      Color.lerp(a.textColor, b.textColor, t)!,
139
      t < 0.5 ? a.style : b.style,
140
      EdgeInsets.lerp(a.margin, b.margin, t)!,
141
      a._position + (b._position - a._position) * t,
142
      (a._opacity + (b._opacity - a._opacity) * t).clamp(0.0, 1.0),
143 144 145 146
    );
  }

  @override
147
  FlutterLogoDecoration? lerpFrom(Decoration? a, double t) {
148
    assert(debugAssertIsValid());
149 150
    if (a == null || a is FlutterLogoDecoration) {
      assert(a == null || a.debugAssertIsValid());
151
      return FlutterLogoDecoration.lerp(a as FlutterLogoDecoration?, this, t);
152
    }
153
    return super.lerpFrom(a, t) as FlutterLogoDecoration?;
154 155 156
  }

  @override
157
  FlutterLogoDecoration? lerpTo(Decoration? b, double t) {
158
    assert(debugAssertIsValid());
159 160
    if (b == null || b is FlutterLogoDecoration) {
      assert(b == null || b.debugAssertIsValid());
161
      return FlutterLogoDecoration.lerp(this, b as FlutterLogoDecoration?, t);
162
    }
163
    return super.lerpTo(b, t) as FlutterLogoDecoration?;
164 165 166 167
  }

  @override
  // TODO(ianh): better hit testing
168
  bool hitTest(Size size, Offset position, { TextDirection? textDirection }) => true;
169 170

  @override
171
  BoxPainter createBoxPainter([ VoidCallback? onChanged ]) {
172
    assert(debugAssertIsValid());
173
    return _FlutterLogoPainter(this);
174 175
  }

176 177 178 179 180
  @override
  Path getClipPath(Rect rect, TextDirection textDirection) {
    return Path()..addRect(rect);
  }

181
  @override
182
  bool operator ==(Object other) {
183
    assert(debugAssertIsValid());
184 185
    if (identical(this, other))
      return true;
186 187 188 189
    return other is FlutterLogoDecoration
        && other.textColor == textColor
        && other._position == _position
        && other._opacity == _opacity;
190 191 192 193
  }

  @override
  int get hashCode {
194
    assert(debugAssertIsValid());
195
    return hashValues(
196
      textColor,
197
      _position,
198
      _opacity,
199 200 201 202
    );
  }

  @override
203 204
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
205
    properties.add(ColorProperty('textColor', textColor));
206
    properties.add(EnumProperty<FlutterLogoStyle>('style', style));
207
    if (_inTransition)
208
      properties.add(DiagnosticsNode.message('transition ${debugFormatDouble(_position)}:${debugFormatDouble(_opacity)}'));
209 210 211 212 213 214
  }
}


/// An object that paints a [BoxDecoration] into a canvas.
class _FlutterLogoPainter extends BoxPainter {
215
  _FlutterLogoPainter(this._config)
216 217 218
      : assert(_config != null),
        assert(_config.debugAssertIsValid()),
        super(null) {
219 220 221 222 223 224
    _prepareText();
  }

  final FlutterLogoDecoration _config;

  // these are configured assuming a font size of 100.0.
225 226
  late TextPainter _textPainter;
  late Rect _textBoundingRect;
227 228 229

  void _prepareText() {
    const String kLabel = 'Flutter';
230 231
    _textPainter = TextPainter(
      text: TextSpan(
232
        text: kLabel,
233
        style: TextStyle(
234
          color: _config.textColor,
235 236 237
          fontFamily: 'Roboto',
          fontSize: 100.0 * 350.0 / 247.0, // 247 is the height of the F when the fontSize is 350, assuming device pixel ratio 1.0
          fontWeight: FontWeight.w300,
Ian Hickson's avatar
Ian Hickson committed
238 239 240 241
          textBaseline: TextBaseline.alphabetic,
        ),
      ),
      textDirection: TextDirection.ltr,
242 243
    );
    _textPainter.layout();
244
    final ui.TextBox textSize = _textPainter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: kLabel.length)).single;
245
    _textBoundingRect = Rect.fromLTRB(textSize.left, textSize.top, textSize.right, textSize.bottom);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  }

  // This class contains a lot of magic numbers. They were derived from the
  // values in the SVG files exported from the original artwork source.

  void _paintLogo(Canvas canvas, Rect rect) {
    // Our points are in a coordinate space that's 166 pixels wide and 202 pixels high.
    // First, transform the rectangle so that our coordinate space is a square 202 pixels
    // to a side, with the top left at the origin.
    canvas.save();
    canvas.translate(rect.left, rect.top);
    canvas.scale(rect.width / 202.0, rect.height / 202.0);
    // Next, offset it some more so that the 166 horizontal pixels are centered
    // in that square (as opposed to being on the left side of it). This means
    // that if we draw in the rectangle from 0,0 to 166,202, we are drawing in
    // the center of the given rect.
    canvas.translate((202.0 - 166.0) / 2.0, 0.0);

    // Set up the styles.
265
    final Paint lightPaint = Paint()
266
      ..color = const Color(0xFF54C5F8);
267
    final Paint mediumPaint = Paint()
268
      ..color = const Color(0xFF29B6F6);
269
    final Paint darkPaint = Paint()
270
      ..color = const Color(0xFF01579B);
271

272
    final ui.Gradient triangleGradient = ui.Gradient.linear(
273 274
      const Offset(87.2623 + 37.9092, 28.8384 + 123.4389),
      const Offset(42.9205 + 37.9092, 35.0952 + 123.4389),
275
      <Color>[
276 277
        const Color(0x001A237E),
        const Color(0x661A237E),
278 279
      ],
    );
280
    final Paint trianglePaint = Paint()
281
      ..shader = triangleGradient;
282 283

    // Draw the basic shape.
284
    final Path topBeam = Path()
285 286 287 288 289 290
      ..moveTo(37.7, 128.9)
      ..lineTo(9.8, 101.0)
      ..lineTo(100.4, 10.4)
      ..lineTo(156.2, 10.4);
    canvas.drawPath(topBeam, lightPaint);

291
    final Path middleBeam = Path()
292 293
      ..moveTo(156.2, 94.0)
      ..lineTo(100.4, 94.0)
294 295
      ..lineTo(78.5, 115.9)
      ..lineTo(106.4, 143.8);
296 297
    canvas.drawPath(middleBeam, lightPaint);

298
    final Path bottomBeam = Path()
299 300 301 302 303 304
      ..moveTo(79.5, 170.7)
      ..lineTo(100.4, 191.6)
      ..lineTo(156.2, 191.6)
      ..lineTo(107.4, 142.8);
    canvas.drawPath(bottomBeam, darkPaint);

305
    // The overlap between middle and bottom beam.
306
    canvas.save();
307
    canvas.transform(Float64List.fromList(const <double>[
308 309 310 311 312 313
      // careful, this is in _column_-major order
      0.7071, -0.7071, 0.0, 0.0,
      0.7071, 0.7071, 0.0, 0.0,
      0.0, 0.0, 1.0, 0.0,
      -77.697, 98.057, 0.0, 1.0,
    ]));
Dan Field's avatar
Dan Field committed
314
    canvas.drawRect(const Rect.fromLTWH(59.8, 123.1, 39.4, 39.4), mediumPaint);
315 316
    canvas.restore();

317
    // The gradients below the middle beam on top of the bottom beam.
318
    final Path triangle = Path()
319 320 321 322 323 324 325 326 327 328 329
      ..moveTo(79.5, 170.7)
      ..lineTo(120.9, 156.4)
      ..lineTo(107.4, 142.8);
    canvas.drawPath(triangle, trianglePaint);

    canvas.restore();
  }

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    offset += _config.margin.topLeft;
330
    final Size canvasSize = _config.margin.deflateSize(configuration.size!);
331 332
    if (canvasSize.isEmpty)
      return;
333
    final Size logoSize;
334 335 336 337 338 339 340 341 342 343
    if (_config._position > 0.0) {
      // horizontal style
      logoSize = const Size(820.0, 232.0);
    } else if (_config._position < 0.0) {
      // stacked style
      logoSize = const Size(252.0, 306.0);
    } else {
      // only the mark
      logoSize = const Size(202.0, 202.0);
    }
344
    final FittedSizes fittedSize = applyBoxFit(BoxFit.contain, logoSize, canvasSize);
345
    assert(fittedSize.source == logoSize);
346
    final Rect rect = Alignment.center.inscribe(fittedSize.destination, offset & canvasSize);
347
    final double centerSquareHeight = canvasSize.shortestSide;
348
    final Rect centerSquare = Rect.fromLTWH(
349 350 351
      offset.dx + (canvasSize.width - centerSquareHeight) / 2.0,
      offset.dy + (canvasSize.height - centerSquareHeight) / 2.0,
      centerSquareHeight,
352
      centerSquareHeight,
353 354
    );

355
    final Rect logoTargetSquare;
356 357
    if (_config._position > 0.0) {
      // horizontal style
358
      logoTargetSquare = Rect.fromLTWH(rect.left, rect.top, rect.height, rect.height);
359 360 361
    } else if (_config._position < 0.0) {
      // stacked style
      final double logoHeight = rect.height * 191.0 / 306.0;
362
      logoTargetSquare = Rect.fromLTWH(
363 364 365
        rect.left + (rect.width - logoHeight) / 2.0,
        rect.top,
        logoHeight,
366
        logoHeight,
367 368 369 370 371
      );
    } else {
      // only the mark
      logoTargetSquare = centerSquare;
    }
372
    final Rect logoSquare = Rect.lerp(centerSquare, logoTargetSquare, _config._position.abs())!;
373 374 375 376

    if (_config._opacity < 1.0) {
      canvas.saveLayer(
        offset & canvasSize,
377 378
        Paint()
          ..colorFilter = ColorFilter.mode(
379
            const Color(0xFFFFFFFF).withOpacity(_config._opacity),
380
            BlendMode.modulate,
381
          ),
382 383 384 385 386 387 388 389 390 391 392 393
      );
    }
    if (_config._position != 0.0) {
      if (_config._position > 0.0) {
        // horizontal style
        final double fontSize = 2.0 / 3.0 * logoSquare.height * (1 - (10.4 * 2.0) / 202.0);
        final double scale = fontSize / 100.0;
        final double finalLeftTextPosition = // position of text in rest position
          (256.4 / 820.0) * rect.width - // 256.4 is the distance from the left edge to the left of the F when the whole logo is 820.0 wide
          (32.0 / 350.0) * fontSize; // 32 is the distance from the text bounding box edge to the left edge of the F when the font size is 350
        final double initialLeftTextPosition = // position of text when just starting the animation
          rect.width / 2.0 - _textBoundingRect.width * scale;
394
        final Offset textOffset = Offset(
395
          rect.left + ui.lerpDouble(initialLeftTextPosition, finalLeftTextPosition, _config._position)!,
396
          rect.top + (rect.height - _textBoundingRect.height * scale) / 2.0,
397 398 399
        );
        canvas.save();
        if (_config._position < 1.0) {
400
          final Offset center = logoSquare.center;
401
          final Path path = Path()
402 403 404
            ..moveTo(center.dx, center.dy)
            ..lineTo(center.dx + rect.width, center.dy - rect.width)
            ..lineTo(center.dx + rect.width, center.dy + rect.width)
405 406 407 408 409 410 411 412 413 414 415 416
            ..close();
          canvas.clipPath(path);
        }
        canvas.translate(textOffset.dx, textOffset.dy);
        canvas.scale(scale, scale);
        _textPainter.paint(canvas, Offset.zero);
        canvas.restore();
      } else if (_config._position < 0.0) {
        // stacked style
        final double fontSize = 0.35 * logoTargetSquare.height * (1 - (10.4 * 2.0) / 202.0);
        final double scale = fontSize / 100.0;
        if (_config._position > -1.0) {
417
          // This limits what the drawRect call below is going to blend with.
418
          canvas.saveLayer(_textBoundingRect, Paint());
419 420 421 422
        } else {
          canvas.save();
        }
        canvas.translate(
423
          logoTargetSquare.center.dx - (_textBoundingRect.width * scale / 2.0),
424
          logoTargetSquare.bottom,
425 426 427 428
        );
        canvas.scale(scale, scale);
        _textPainter.paint(canvas, Offset.zero);
        if (_config._position > -1.0) {
429
          canvas.drawRect(_textBoundingRect.inflate(_textBoundingRect.width * 0.5), Paint()
430
            ..blendMode = BlendMode.modulate
431 432 433
            ..shader = ui.Gradient.linear(
              Offset(_textBoundingRect.width * -0.5, 0.0),
              Offset(_textBoundingRect.width * 1.5, 0.0),
434 435
              <Color>[const Color(0xFFFFFFFF), const Color(0xFFFFFFFF), const Color(0x00FFFFFF), const Color(0x00FFFFFF)],
              <double>[ 0.0, math.max(0.0, _config._position.abs() - 0.1), math.min(_config._position.abs() + 0.1, 1.0), 1.0 ],
436
            ),
437 438 439 440 441 442 443 444 445 446
          );
        }
        canvas.restore();
      }
    }
    _paintLogo(canvas, logoSquare);
    if (_config._opacity < 1.0)
      canvas.restore();
  }
}