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

import 'dart:math' as math;

7
import 'package:flutter/foundation.dart';
8

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

Florian Loitsch's avatar
Florian Loitsch committed
20
/// An immutable description of how to paint a box.
21
///
Ian Hickson's avatar
Ian Hickson committed
22 23
/// The [BoxDecoration] class provides a variety of ways to draw a box.
///
24
/// The box has a [border], a body, and may cast a [boxShadow].
Ian Hickson's avatar
Ian Hickson committed
25 26 27 28 29 30 31 32 33
///
/// 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.
///
34
/// The [border] paints over the body; the [boxShadow], naturally, paints below it.
Ian Hickson's avatar
Ian Hickson committed
35
///
36
/// {@tool snippet}
Ian Hickson's avatar
Ian Hickson committed
37
///
38 39 40 41
/// 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)
42 43
///
/// ```dart
44 45
/// Container(
///   decoration: BoxDecoration(
46
///     color: const Color(0xff7c94b6),
47
///     image: const DecorationImage(
48
///       image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
49
///       fit: BoxFit.cover,
50
///     ),
51
///     border: Border.all(
52
///       color: Colors.black,
53
///       width: 8,
54
///     ),
55
///     borderRadius: BorderRadius.circular(12),
56 57 58
///   ),
/// )
/// ```
59
/// {@end-tool}
Ian Hickson's avatar
Ian Hickson committed
60
///
61
/// {@template flutter.painting.BoxDecoration.clip}
62 63 64 65 66 67
/// 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
68 69 70 71 72 73
/// 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.
74
class BoxDecoration extends Decoration {
75 76
  /// Creates a box decoration.
  ///
77 78
  /// * If [color] is null, this decoration does not paint a background color.
  /// * If [image] is null, this decoration does not paint a background image.
79
  /// * If [border] is null, this decoration does not paint a border.
80
  /// * If [borderRadius] is null, this decoration uses more efficient background
81
  ///   painting commands. The [borderRadius] argument must be null if [shape] is
82 83 84
  ///   [BoxShape.circle].
  /// * If [boxShadow] is null, this decoration does not paint a shadow.
  /// * If [gradient] is null, this decoration does not paint gradients.
85
  /// * If [backgroundBlendMode] is null, this decoration paints with [BlendMode.srcOver]
86 87
  ///
  /// The [shape] argument must not be null.
88
  const BoxDecoration({
89 90
    this.color,
    this.image,
91 92 93 94
    this.border,
    this.borderRadius,
    this.boxShadow,
    this.gradient,
95
    this.backgroundBlendMode,
96
    this.shape = BoxShape.rectangle,
97 98
  }) : assert(shape != null),
       assert(
99
         backgroundBlendMode == null || color != null || gradient != null,
100
         "backgroundBlendMode applies to BoxDecoration's background color or "
101
         'gradient, but no color or gradient was provided.',
102
       );
103

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

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

Florian Loitsch's avatar
Florian Loitsch committed
134
  /// The color to fill in the background of the box.
135
  ///
136 137 138 139 140 141
  /// 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].
142
  final Color? color;
143

144 145 146 147 148
  /// 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.
149
  final DecorationImage? image;
150

151 152 153
  /// A border to draw above the background [color], [gradient], or [image].
  ///
  /// Follows the [shape] and [borderRadius].
Ian Hickson's avatar
Ian Hickson committed
154 155 156 157 158 159 160
  ///
  /// 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.
161
  final BoxBorder? border;
162

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

171 172 173
  /// 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
174 175 176 177 178 179
  ///
  /// See also:
  ///
  ///  * [kElevationToShadow], for some predefined shadows used in Material
  ///    Design.
  ///  * [PhysicalModel], a widget for showing shadows.
180
  final List<BoxShadow>? boxShadow;
181

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

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

197 198 199
  /// The shape to fill the background [color], [gradient], and [image] into and
  /// to cast as the [boxShadow].
  ///
200 201 202 203 204 205 206 207
  /// 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].
208
  ///
209
  /// {@macro flutter.painting.BoxDecoration.clip}
210
  final BoxShape shape;
211

212
  @override
213
  EdgeInsetsGeometry? get padding => border?.dimensions;
214

215
  @override
216
  Path getClipPath(Rect rect, TextDirection textDirection) {
217 218
    switch (shape) {
      case BoxShape.circle:
219 220 221
        final Offset center = rect.center;
        final double radius = rect.shortestSide / 2.0;
        final Rect square = Rect.fromCircle(center: center, radius: radius);
222
        return Path()..addOval(square);
223 224
      case BoxShape.rectangle:
        if (borderRadius != null)
225 226
          return Path()..addRRect(borderRadius!.resolve(textDirection).toRRect(rect));
        return Path()..addRect(rect);
227 228 229
    }
  }

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

243 244 245
  @override
  bool get isComplex => boxShadow != null;

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

  @override
256
  BoxDecoration? lerpTo(Decoration? b, double t) {
257 258
    if (b == null)
      return scale(1.0 - t);
259 260
    if (b is BoxDecoration)
      return BoxDecoration.lerp(this, b, t);
261
    return super.lerpTo(b, t) as BoxDecoration?;
262 263
  }

264
  /// Linearly interpolate between two box decorations.
265 266
  ///
  /// Interpolates each parameter of the box decoration separately.
267
  ///
268 269 270 271 272 273 274 275 276 277
  /// 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.
  ///
278
  /// {@macro dart.ui.shadow.lerp}
279
  ///
280 281 282 283 284
  /// 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]
285
  ///    and which use [BoxDecoration.lerp] when interpolating two
286
  ///    [BoxDecoration]s or a [BoxDecoration] to or from null.
287
  static BoxDecoration? lerp(BoxDecoration? a, BoxDecoration? b, double t) {
288
    assert(t != null);
289 290 291
    if (a == null && b == null)
      return null;
    if (a == null)
292
      return b!.scale(t);
293 294
    if (b == null)
      return a.scale(1.0 - t);
295 296 297 298
    if (t == 0.0)
      return a;
    if (t == 1.0)
      return b;
299
    return BoxDecoration(
300
      color: Color.lerp(a.color, b.color, t),
301
      image: t < 0.5 ? a.image : b.image, // TODO(ianh): cross-fade the image
Ian Hickson's avatar
Ian Hickson committed
302
      border: BoxBorder.lerp(a.border, b.border, t),
303
      borderRadius: BorderRadiusGeometry.lerp(a.borderRadius, b.borderRadius, t),
304
      boxShadow: BoxShadow.lerpList(a.boxShadow, b.boxShadow, t),
305
      gradient: Gradient.lerp(a.gradient, b.gradient, t),
306
      shape: t < 0.5 ? a.shape : b.shape,
307 308 309
    );
  }

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

327
  @override
328 329 330 331 332 333 334
  int get hashCode => Object.hash(
    color,
    image,
    border,
    borderRadius,
    boxShadow == null ? null : Object.hashAll(boxShadow!),
    gradient,
335
    backgroundBlendMode,
336 337
    shape,
  );
338

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

346
    properties.add(ColorProperty('color', color, defaultValue: null));
347 348 349 350 351 352
    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));
353
  }
354

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

374
  @override
375
  BoxPainter createBoxPainter([ VoidCallback? onChanged ]) {
376
    assert(onChanged != null || image == null);
377
    return _BoxDecorationPainter(this, onChanged);
378
  }
379 380
}

Florian Loitsch's avatar
Florian Loitsch committed
381
/// An object that paints a [BoxDecoration] into a canvas.
382
class _BoxDecorationPainter extends BoxPainter {
383
  _BoxDecorationPainter(this._decoration, VoidCallback? onChanged)
384
    : assert(_decoration != null),
385
      super(onChanged);
386

387
  final BoxDecoration _decoration;
388

389 390 391
  Paint? _cachedBackgroundPaint;
  Rect? _rectForCachedBackgroundPaint;
  Paint _getBackgroundPaint(Rect rect, TextDirection? textDirection) {
392
    assert(rect != null);
393 394
    assert(_decoration.gradient != null || _rectForCachedBackgroundPaint == null);

395 396
    if (_cachedBackgroundPaint == null ||
        (_decoration.gradient != null && _rectForCachedBackgroundPaint != rect)) {
397
      final Paint paint = Paint();
398
      if (_decoration.backgroundBlendMode != null)
399
        paint.blendMode = _decoration.backgroundBlendMode!;
400
      if (_decoration.color != null)
401
        paint.color = _decoration.color!;
402
      if (_decoration.gradient != null) {
403
        paint.shader = _decoration.gradient!.createShader(rect, textDirection: textDirection);
404 405
        _rectForCachedBackgroundPaint = rect;
      }
406 407 408
      _cachedBackgroundPaint = paint;
    }

409
    return _cachedBackgroundPaint!;
410 411
  }

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

430
  void _paintShadows(Canvas canvas, Rect rect, TextDirection? textDirection) {
Hans Muller's avatar
Hans Muller committed
431 432
    if (_decoration.boxShadow == null)
      return;
433
    for (final BoxShadow boxShadow in _decoration.boxShadow!) {
434
      final Paint paint = boxShadow.toPaint();
Hans Muller's avatar
Hans Muller committed
435
      final Rect bounds = rect.shift(boxShadow.offset).inflate(boxShadow.spreadRadius);
436
      _paintBox(canvas, bounds, paint, textDirection);
Hans Muller's avatar
Hans Muller committed
437 438 439
    }
  }

440
  void _paintBackgroundColor(Canvas canvas, Rect rect, TextDirection? textDirection) {
441
    if (_decoration.color != null || _decoration.gradient != null)
442
      _paintBox(canvas, rect, _getBackgroundPaint(rect, textDirection), textDirection);
Hans Muller's avatar
Hans Muller committed
443 444
  }

445
  DecorationImagePainter? _imagePainter;
446
  void _paintBackgroundImage(Canvas canvas, Rect rect, ImageConfiguration configuration) {
447
    if (_decoration.image == null)
448
      return;
449 450
    _imagePainter ??= _decoration.image!.createPainter(onChanged!);
    Path? clipPath;
451 452
    switch (_decoration.shape) {
      case BoxShape.circle:
453 454 455 456 457
        assert(_decoration.borderRadius == null);
        final Offset center = rect.center;
        final double radius = rect.shortestSide / 2.0;
        final Rect square = Rect.fromCircle(center: center, radius: radius);
        clipPath = Path()..addOval(square);
458 459 460
        break;
      case BoxShape.rectangle:
        if (_decoration.borderRadius != null)
461
          clipPath = Path()..addRRect(_decoration.borderRadius!.resolve(configuration.textDirection).toRRect(rect));
462
        break;
463
    }
464
    _imagePainter!.paint(canvas, rect, clipPath, configuration);
465 466 467 468
  }

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

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

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