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
// 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;

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

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

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

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

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

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

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

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

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

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

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

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

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

214
  @override
215
  EdgeInsetsGeometry? get padding => border?.dimensions;
216

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

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

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

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

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

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

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

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

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

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

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

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

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

389
  final BoxDecoration _decoration;
390

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

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

411
    return _cachedBackgroundPaint!;
412 413
  }

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

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

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

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

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

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

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