box_decoration.dart 17.2 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
// @dart = 2.8

7 8
import 'dart:math' as math;

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

11
import 'basic_types.dart';
12
import 'border_radius.dart';
13
import 'box_border.dart';
14
import 'box_shadow.dart';
15
import 'colors.dart';
16
import 'decoration.dart';
17
import 'decoration_image.dart';
18
import 'edge_insets.dart';
19
import 'gradient.dart';
20
import 'image_provider.dart';
21

Florian Loitsch's avatar
Florian Loitsch committed
22
/// An immutable description of how to paint a box.
23
///
Ian Hickson's avatar
Ian Hickson committed
24 25
/// The [BoxDecoration] class provides a variety of ways to draw a box.
///
26
/// The box has a [border], a body, and may cast a [boxShadow].
Ian Hickson's avatar
Ian Hickson committed
27 28 29 30 31 32 33 34 35
///
/// The [shape] of the box can be a circle or a rectangle. If it is a rectangle,
/// then the [borderRadius] property controls the roundness of the corners.
///
/// The body of the box is painted in layers. The bottom-most layer is the
/// [color], which fills the box. Above that is the [gradient], which also fills
/// the box. Finally there is the [image], the precise alignment of which is
/// controlled by the [DecorationImage] class.
///
36
/// The [border] paints over the body; the [boxShadow], naturally, paints below it.
Ian Hickson's avatar
Ian Hickson committed
37
///
38
/// {@tool snippet}
Ian Hickson's avatar
Ian Hickson committed
39
///
40 41 42 43
/// The following applies a [BoxDecoration] to a [Container] widget to draw an
/// [image] of an owl with a thick black [border] and rounded corners.
///
/// ![](https://flutter.github.io/assets-for-api-docs/assets/painting/box_decoration.png)
44 45
///
/// ```dart
46 47
/// Container(
///   decoration: BoxDecoration(
48
///     color: const Color(0xff7c94b6),
49
///     image: const DecorationImage(
50
///       image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
51
///       fit: BoxFit.cover,
52
///     ),
53
///     border: Border.all(
54
///       color: Colors.black,
55
///       width: 8,
56
///     ),
57
///     borderRadius: BorderRadius.circular(12),
58 59 60
///   ),
/// )
/// ```
61
/// {@end-tool}
Ian Hickson's avatar
Ian Hickson committed
62
///
63 64 65 66 67 68 69
/// {@template flutter.painting.boxDecoration.clip}
/// The [shape] or the [borderRadius] won't clip the children of the
/// decorated [Container]. If the clip is required, insert a clip widget
/// (e.g., [ClipRect], [ClipRRect], [ClipPath]) as the child of the [Container].
/// Be aware that clipping may be costly in terms of performance.
/// {@endtemplate}
///
Ian Hickson's avatar
Ian Hickson committed
70 71 72 73 74 75
/// See also:
///
///  * [DecoratedBox] and [Container], widgets that can be configured with
///    [BoxDecoration] objects.
///  * [CustomPaint], a widget that lets you draw arbitrary graphics.
///  * [Decoration], the base class which lets you define other decorations.
76
class BoxDecoration extends Decoration {
77 78
  /// Creates a box decoration.
  ///
79 80
  /// * If [color] is null, this decoration does not paint a background color.
  /// * If [image] is null, this decoration does not paint a background image.
81
  /// * If [border] is null, this decoration does not paint a border.
82
  /// * If [borderRadius] is null, this decoration uses more efficient background
83
  ///   painting commands. The [borderRadius] argument must be null if [shape] is
84 85 86
  ///   [BoxShape.circle].
  /// * If [boxShadow] is null, this decoration does not paint a shadow.
  /// * If [gradient] is null, this decoration does not paint gradients.
87
  /// * If [backgroundBlendMode] is null, this decoration paints with [BlendMode.srcOver]
88 89
  ///
  /// The [shape] argument must not be null.
90
  const BoxDecoration({
91 92
    this.color,
    this.image,
93 94 95 96
    this.border,
    this.borderRadius,
    this.boxShadow,
    this.gradient,
97
    this.backgroundBlendMode,
98
    this.shape = BoxShape.rectangle,
99 100
  }) : assert(shape != null),
       assert(
101
         backgroundBlendMode == null || color != null || gradient != null,
102
         "backgroundBlendMode applies to BoxDecoration's background color or "
103
         'gradient, but no color or gradient was provided.'
104
       );
105

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
  /// Creates a copy of this object but with the given fields replaced with the
  /// new values.
  BoxDecoration copyWith({
    Color color,
    DecorationImage image,
    BoxBorder border,
    BorderRadiusGeometry borderRadius,
    List<BoxShadow> boxShadow,
    Gradient gradient,
    BlendMode backgroundBlendMode,
    BoxShape shape,
  }) {
    return BoxDecoration(
      color: color ?? this.color,
      image: image ?? this.image,
      border: border ?? this.border,
      borderRadius: borderRadius ?? this.borderRadius,
      boxShadow: boxShadow ?? this.boxShadow,
      gradient: gradient ?? this.gradient,
      backgroundBlendMode: backgroundBlendMode ?? this.backgroundBlendMode,
      shape: shape ?? this.shape,
    );
  }

130
  @override
131
  bool debugAssertIsValid() {
132
    assert(shape != BoxShape.circle ||
133
          borderRadius == null); // Can't have a border radius if you're a circle.
134
    return super.debugAssertIsValid();
135 136
  }

Florian Loitsch's avatar
Florian Loitsch committed
137
  /// The color to fill in the background of the box.
138
  ///
139 140 141 142 143 144
  /// The color is filled into the [shape] of the box (e.g., either a rectangle,
  /// potentially with a [borderRadius], or a circle).
  ///
  /// This is ignored if [gradient] is non-null.
  ///
  /// The [color] is drawn under the [image].
145
  final Color color;
146

147 148 149 150 151
  /// An image to paint above the background [color] or [gradient].
  ///
  /// If [shape] is [BoxShape.circle] then the image is clipped to the circle's
  /// boundary; if [borderRadius] is non-null then the image is clipped to the
  /// given radii.
152
  final DecorationImage image;
153

154 155 156
  /// A border to draw above the background [color], [gradient], or [image].
  ///
  /// Follows the [shape] and [borderRadius].
Ian Hickson's avatar
Ian Hickson committed
157 158 159 160 161 162 163 164
  ///
  /// Use [Border] objects to describe borders that do not depend on the reading
  /// direction.
  ///
  /// Use [BoxBorder] objects to describe borders that should flip their left
  /// and right edges based on whether the text is being read left-to-right or
  /// right-to-left.
  final BoxBorder border;
165

166
  /// If non-null, the corners of this box are rounded by this [BorderRadius].
167
  ///
168 169
  /// Applies only to boxes with rectangular shapes; ignored if [shape] is not
  /// [BoxShape.rectangle].
170 171
  ///
  /// {@macro flutter.painting.boxDecoration.clip}
172
  final BorderRadiusGeometry borderRadius;
173

174 175 176
  /// A list of shadows cast by this box behind the box.
  ///
  /// The shadow follows the [shape] of the box.
Ian Hickson's avatar
Ian Hickson committed
177 178 179 180 181 182
  ///
  /// See also:
  ///
  ///  * [kElevationToShadow], for some predefined shadows used in Material
  ///    Design.
  ///  * [PhysicalModel], a widget for showing shadows.
183
  final List<BoxShadow> boxShadow;
184

185
  /// A gradient to use when filling the box.
186 187 188 189
  ///
  /// If this is specified, [color] has no effect.
  ///
  /// The [gradient] is drawn under the [image].
190
  final Gradient gradient;
191

192 193
  /// The blend mode applied to the [color] or [gradient] background of the box.
  ///
194
  /// If no [backgroundBlendMode] is provided then the default painting blend
195 196
  /// mode is used.
  ///
197
  /// If no [color] or [gradient] is provided then the blend mode has no impact.
198 199
  final BlendMode backgroundBlendMode;

200 201 202
  /// The shape to fill the background [color], [gradient], and [image] into and
  /// to cast as the [boxShadow].
  ///
203 204 205 206 207 208 209 210
  /// If this is [BoxShape.circle] then [borderRadius] is ignored.
  ///
  /// The [shape] cannot be interpolated; animating between two [BoxDecoration]s
  /// with different [shape]s will result in a discontinuity in the rendering.
  /// To interpolate between two shapes, consider using [ShapeDecoration] and
  /// different [ShapeBorder]s; in particular, [CircleBorder] instead of
  /// [BoxShape.circle] and [RoundedRectangleBorder] instead of
  /// [BoxShape.rectangle].
211 212
  ///
  /// {@macro flutter.painting.boxDecoration.clip}
213
  final BoxShape shape;
214

215
  @override
Ian Hickson's avatar
Ian Hickson committed
216
  EdgeInsetsGeometry get padding => border?.dimensions;
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
  @override
  Path getClipPath(Rect rect, TextDirection textDirection) {
    Path clipPath;
    switch (shape) {
      case BoxShape.circle:
        clipPath = Path()..addOval(rect);
        break;
      case BoxShape.rectangle:
        if (borderRadius != null)
          clipPath = Path()..addRRect(borderRadius.resolve(textDirection).toRRect(rect));
        break;
    }
    return clipPath;
  }

Florian Loitsch's avatar
Florian Loitsch committed
233
  /// Returns a new box decoration that is scaled by the given factor.
234
  BoxDecoration scale(double factor) {
235
    return BoxDecoration(
236
      color: Color.lerp(null, color, factor),
237
      image: image, // TODO(ianh): fade the image from transparent
Ian Hickson's avatar
Ian Hickson committed
238
      border: BoxBorder.lerp(null, border, factor),
239
      borderRadius: BorderRadiusGeometry.lerp(null, borderRadius, factor),
240
      boxShadow: BoxShadow.lerpList(null, boxShadow, factor),
241
      gradient: gradient?.scale(factor),
242
      shape: shape,
243 244 245
    );
  }

246 247 248
  @override
  bool get isComplex => boxShadow != null;

249 250
  @override
  BoxDecoration lerpFrom(Decoration a, double t) {
251 252
    if (a == null)
      return scale(t);
253 254
    if (a is BoxDecoration)
      return BoxDecoration.lerp(a, this, t);
255
    return super.lerpFrom(a, t) as BoxDecoration;
256 257 258 259
  }

  @override
  BoxDecoration lerpTo(Decoration b, double t) {
260 261
    if (b == null)
      return scale(1.0 - t);
262 263
    if (b is BoxDecoration)
      return BoxDecoration.lerp(this, b, t);
264
    return super.lerpTo(b, t) as BoxDecoration;
265 266
  }

267
  /// Linearly interpolate between two box decorations.
268 269
  ///
  /// Interpolates each parameter of the box decoration separately.
270
  ///
271 272 273 274 275 276 277 278 279 280
  /// The [shape] is not interpolated. To interpolate the shape, consider using
  /// a [ShapeDecoration] with different border shapes.
  ///
  /// 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
  /// by applying [scale] to the other value. If neither value is null and `t ==
  /// 0.0`, then `a` is returned unmodified; if `t == 1.0` then `b` is returned
  /// unmodified. Otherwise, the values are computed by interpolating the
  /// properties appropriately.
  ///
281
  /// {@macro dart.ui.shadow.lerp}
282
  ///
283 284 285 286 287
  /// See also:
  ///
  ///  * [Decoration.lerp], which can interpolate between any two types of
  ///    [Decoration]s, not just [BoxDecoration]s.
  ///  * [lerpFrom] and [lerpTo], which are used to implement [Decoration.lerp]
288
  ///    and which use [BoxDecoration.lerp] when interpolating two
289
  ///    [BoxDecoration]s or a [BoxDecoration] to or from null.
290
  static BoxDecoration lerp(BoxDecoration a, BoxDecoration b, double t) {
291
    assert(t != null);
292 293 294 295 296 297
    if (a == null && b == null)
      return null;
    if (a == null)
      return b.scale(t);
    if (b == null)
      return a.scale(1.0 - t);
298 299 300 301
    if (t == 0.0)
      return a;
    if (t == 1.0)
      return b;
302
    return BoxDecoration(
303
      color: Color.lerp(a.color, b.color, t),
304
      image: t < 0.5 ? a.image : b.image, // TODO(ianh): cross-fade the image
Ian Hickson's avatar
Ian Hickson committed
305
      border: BoxBorder.lerp(a.border, b.border, t),
306
      borderRadius: BorderRadiusGeometry.lerp(a.borderRadius, b.borderRadius, t),
307
      boxShadow: BoxShadow.lerpList(a.boxShadow, b.boxShadow, t),
308
      gradient: Gradient.lerp(a.gradient, b.gradient, t),
309
      shape: t < 0.5 ? a.shape : b.shape,
310 311 312
    );
  }

313
  @override
314
  bool operator ==(Object other) {
315 316
    if (identical(this, other))
      return true;
317
    if (other.runtimeType != runtimeType)
318
      return false;
319 320 321 322 323
    return other is BoxDecoration
        && other.color == color
        && other.image == image
        && other.border == border
        && other.borderRadius == borderRadius
324
        && listEquals<BoxShadow>(other.boxShadow, boxShadow)
325 326
        && other.gradient == gradient
        && other.shape == shape;
327 328
  }

329
  @override
330
  int get hashCode {
331
    return hashValues(
332 333
      color,
      image,
334 335
      border,
      borderRadius,
336
      hashList(boxShadow),
337
      gradient,
338
      shape,
339
    );
340 341
  }

342
  @override
343 344 345 346 347 348
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties
      ..defaultDiagnosticsTreeStyle = DiagnosticsTreeStyle.whitespace
      ..emptyBodyDescription = '<no decorations specified>';

349
    properties.add(ColorProperty('color', color, defaultValue: null));
350 351 352 353 354 355
    properties.add(DiagnosticsProperty<DecorationImage>('image', image, defaultValue: null));
    properties.add(DiagnosticsProperty<BoxBorder>('border', border, defaultValue: null));
    properties.add(DiagnosticsProperty<BorderRadiusGeometry>('borderRadius', borderRadius, defaultValue: null));
    properties.add(IterableProperty<BoxShadow>('boxShadow', boxShadow, defaultValue: null, style: DiagnosticsTreeStyle.whitespace));
    properties.add(DiagnosticsProperty<Gradient>('gradient', gradient, defaultValue: null));
    properties.add(EnumProperty<BoxShape>('shape', shape, defaultValue: BoxShape.rectangle));
356
  }
357

358
  @override
359
  bool hitTest(Size size, Offset position, { TextDirection textDirection }) {
360
    assert(shape != null);
361
    assert((Offset.zero & size).contains(position));
362 363 364
    switch (shape) {
      case BoxShape.rectangle:
        if (borderRadius != null) {
365
          final RRect bounds = borderRadius.resolve(textDirection).toRRect(Offset.zero & size);
366 367 368 369 370
          return bounds.contains(position);
        }
        return true;
      case BoxShape.circle:
        // Circles are inscribed into our smallest dimension.
371
        final Offset center = size.center(Offset.zero);
372
        final double distance = (position - center).distance;
373 374
        return distance <= math.min(size.width, size.height) / 2.0;
    }
pq's avatar
pq committed
375
    assert(shape != null);
pq's avatar
pq committed
376
    return null;
377 378
  }

379
  @override
380
  _BoxDecorationPainter createBoxPainter([ VoidCallback onChanged ]) {
381
    assert(onChanged != null || image == null);
382
    return _BoxDecorationPainter(this, onChanged);
383
  }
384 385
}

Florian Loitsch's avatar
Florian Loitsch committed
386
/// An object that paints a [BoxDecoration] into a canvas.
387
class _BoxDecorationPainter extends BoxPainter {
388
  _BoxDecorationPainter(this._decoration, VoidCallback onChanged)
389
    : assert(_decoration != null),
390
      super(onChanged);
391

392
  final BoxDecoration _decoration;
393 394

  Paint _cachedBackgroundPaint;
395
  Rect _rectForCachedBackgroundPaint;
396
  Paint _getBackgroundPaint(Rect rect, TextDirection textDirection) {
397
    assert(rect != null);
398 399
    assert(_decoration.gradient != null || _rectForCachedBackgroundPaint == null);

400 401
    if (_cachedBackgroundPaint == null ||
        (_decoration.gradient != null && _rectForCachedBackgroundPaint != rect)) {
402
      final Paint paint = Paint();
403 404
      if (_decoration.backgroundBlendMode != null)
        paint.blendMode = _decoration.backgroundBlendMode;
405 406
      if (_decoration.color != null)
        paint.color = _decoration.color;
407
      if (_decoration.gradient != null) {
408
        paint.shader = _decoration.gradient.createShader(rect, textDirection: textDirection);
409 410
        _rectForCachedBackgroundPaint = rect;
      }
411 412 413 414 415 416
      _cachedBackgroundPaint = paint;
    }

    return _cachedBackgroundPaint;
  }

417
  void _paintBox(Canvas canvas, Rect rect, Paint paint, TextDirection textDirection) {
Hans Muller's avatar
Hans Muller committed
418
    switch (_decoration.shape) {
419
      case BoxShape.circle:
Hans Muller's avatar
Hans Muller committed
420
        assert(_decoration.borderRadius == null);
421
        final Offset center = rect.center;
422
        final double radius = rect.shortestSide / 2.0;
Hans Muller's avatar
Hans Muller committed
423 424
        canvas.drawCircle(center, radius, paint);
        break;
425
      case BoxShape.rectangle:
Hans Muller's avatar
Hans Muller committed
426 427 428
        if (_decoration.borderRadius == null) {
          canvas.drawRect(rect, paint);
        } else {
429
          canvas.drawRRect(_decoration.borderRadius.resolve(textDirection).toRRect(rect), paint);
Hans Muller's avatar
Hans Muller committed
430 431
        }
        break;
432 433 434
    }
  }

435
  void _paintShadows(Canvas canvas, Rect rect, TextDirection textDirection) {
Hans Muller's avatar
Hans Muller committed
436 437
    if (_decoration.boxShadow == null)
      return;
438
    for (final BoxShadow boxShadow in _decoration.boxShadow) {
439
      final Paint paint = boxShadow.toPaint();
Hans Muller's avatar
Hans Muller committed
440
      final Rect bounds = rect.shift(boxShadow.offset).inflate(boxShadow.spreadRadius);
441
      _paintBox(canvas, bounds, paint, textDirection);
Hans Muller's avatar
Hans Muller committed
442 443 444
    }
  }

445
  void _paintBackgroundColor(Canvas canvas, Rect rect, TextDirection textDirection) {
446
    if (_decoration.color != null || _decoration.gradient != null)
447
      _paintBox(canvas, rect, _getBackgroundPaint(rect, textDirection), textDirection);
Hans Muller's avatar
Hans Muller committed
448 449
  }

450
  DecorationImagePainter _imagePainter;
451
  void _paintBackgroundImage(Canvas canvas, Rect rect, ImageConfiguration configuration) {
452
    if (_decoration.image == null)
453
      return;
454
    _imagePainter ??= _decoration.image.createPainter(onChanged);
455
    Path clipPath;
456 457
    switch (_decoration.shape) {
      case BoxShape.circle:
458
        clipPath = Path()..addOval(rect);
459 460 461
        break;
      case BoxShape.rectangle:
        if (_decoration.borderRadius != null)
462
          clipPath = Path()..addRRect(_decoration.borderRadius.resolve(configuration.textDirection).toRRect(rect));
463
        break;
464
    }
465
    _imagePainter.paint(canvas, rect, clipPath, configuration);
466 467 468 469
  }

  @override
  void dispose() {
470
    _imagePainter?.dispose();
471 472 473
    super.dispose();
  }

474
  /// Paint the box decoration into the given location on the given canvas
475
  @override
476 477 478 479
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    assert(configuration != null);
    assert(configuration.size != null);
    final Rect rect = offset & configuration.size;
480 481 482
    final TextDirection textDirection = configuration.textDirection;
    _paintShadows(canvas, rect, textDirection);
    _paintBackgroundColor(canvas, rect, textDirection);
483
    _paintBackgroundImage(canvas, rect, configuration);
484 485 486 487
    _decoration.border?.paint(
      canvas,
      rect,
      shape: _decoration.shape,
488
      borderRadius: _decoration.borderRadius as BorderRadius,
Ian Hickson's avatar
Ian Hickson committed
489
      textDirection: configuration.textDirection,
490
    );
491
  }
492 493 494 495 496

  @override
  String toString() {
    return 'BoxPainter for $_decoration';
  }
497
}