decoration_image.dart 25.7 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
import 'dart:developer' as developer;
7 8 9
import 'dart:ui' as ui show Image;

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

12
import 'alignment.dart';
13
import 'basic_types.dart';
14
import 'binding.dart';
15
import 'borders.dart';
16
import 'box_fit.dart';
17
import 'debug.dart';
18 19
import 'image_provider.dart';
import 'image_stream.dart';
20 21 22 23 24 25 26 27 28 29 30 31

/// How to paint any portions of a box not covered by an image.
enum ImageRepeat {
  /// Repeat the image in both the x and y directions until the box is filled.
  repeat,

  /// Repeat the image in the x direction until the box is filled horizontally.
  repeatX,

  /// Repeat the image in the y direction until the box is filled vertically.
  repeatY,

32
  /// Leave uncovered portions of the box transparent.
33
  noRepeat,
34 35 36 37 38 39 40 41 42 43
}

/// An image for a box decoration.
///
/// The image is painted using [paintImage], which describes the meanings of the
/// various fields on this class in more detail.
@immutable
class DecorationImage {
  /// Creates an image to show in a [BoxDecoration].
  ///
Ian Hickson's avatar
Ian Hickson committed
44 45
  /// The [image], [alignment], [repeat], and [matchTextDirection] arguments
  /// must not be null.
46
  const DecorationImage({
47
    required this.image,
48
    this.onError,
49 50
    this.colorFilter,
    this.fit,
51
    this.alignment = Alignment.center,
52
    this.centerSlice,
53 54
    this.repeat = ImageRepeat.noRepeat,
    this.matchTextDirection = false,
55
    this.scale = 1.0,
56 57 58 59
    this.opacity = 1.0,
    this.filterQuality = FilterQuality.low,
    this.invertColors = false,
    this.isAntiAlias = false,
Ian Hickson's avatar
Ian Hickson committed
60 61 62
  }) : assert(image != null),
       assert(alignment != null),
       assert(repeat != null),
63 64
       assert(matchTextDirection != null),
       assert(scale != null);
65 66 67 68 69 70 71

  /// The image to be painted into the decoration.
  ///
  /// Typically this will be an [AssetImage] (for an image shipped with the
  /// application) or a [NetworkImage] (for an image obtained from the network).
  final ImageProvider image;

72
  /// An optional error callback for errors emitted when loading [image].
73
  final ImageErrorListener? onError;
74

75
  /// A color filter to apply to the image before painting it.
76
  final ColorFilter? colorFilter;
77 78 79 80 81 82 83

  /// How the image should be inscribed into the box.
  ///
  /// The default is [BoxFit.scaleDown] if [centerSlice] is null, and
  /// [BoxFit.fill] if [centerSlice] is not null.
  ///
  /// See the discussion at [paintImage] for more details.
84
  final BoxFit? fit;
85 86 87

  /// How to align the image within its bounds.
  ///
Ian Hickson's avatar
Ian Hickson committed
88
  /// The alignment aligns the given position in the image to the given position
89
  /// in the layout bounds. For example, an [Alignment] alignment of (-1.0,
90 91
  /// -1.0) aligns the image to the top-left corner of its layout bounds, while a
  /// [Alignment] alignment of (1.0, 1.0) aligns the bottom right of the
Ian Hickson's avatar
Ian Hickson committed
92
  /// image with the bottom right corner of its layout bounds. Similarly, an
93
  /// alignment of (0.0, 1.0) aligns the bottom middle of the image with the
Ian Hickson's avatar
Ian Hickson committed
94 95 96 97 98 99
  /// middle of the bottom edge of its layout bounds.
  ///
  /// To display a subpart of an image, consider using a [CustomPainter] and
  /// [Canvas.drawImageRect].
  ///
  /// If the [alignment] is [TextDirection]-dependent (i.e. if it is a
100
  /// [AlignmentDirectional]), then a [TextDirection] must be available
Ian Hickson's avatar
Ian Hickson committed
101
  /// when the image is painted.
102
  ///
103
  /// Defaults to [Alignment.center].
104 105 106 107 108 109 110
  ///
  /// See also:
  ///
  ///  * [Alignment], a class with convenient constants typically used to
  ///    specify an [AlignmentGeometry].
  ///  * [AlignmentDirectional], like [Alignment] for specifying alignments
  ///    relative to text direction.
111
  final AlignmentGeometry alignment;
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

  /// The center slice for a nine-patch image.
  ///
  /// The region of the image inside the center slice will be stretched both
  /// horizontally and vertically to fit the image into its destination. The
  /// region of the image above and below the center slice will be stretched
  /// only horizontally and the region of the image to the left and right of
  /// the center slice will be stretched only vertically.
  ///
  /// The stretching will be applied in order to make the image fit into the box
  /// specified by [fit]. When [centerSlice] is not null, [fit] defaults to
  /// [BoxFit.fill], which distorts the destination image size relative to the
  /// image's original aspect ratio. Values of [BoxFit] which do not distort the
  /// destination image size will result in [centerSlice] having no effect
  /// (since the nine regions of the image will be rendered with the same
  /// scaling, as if it wasn't specified).
128
  final Rect? centerSlice;
129 130 131 132 133

  /// How to paint any portions of the box that would not otherwise be covered
  /// by the image.
  final ImageRepeat repeat;

Ian Hickson's avatar
Ian Hickson committed
134 135 136 137 138 139 140 141 142
  /// Whether to paint the image in the direction of the [TextDirection].
  ///
  /// If this is true, then in [TextDirection.ltr] contexts, the image will be
  /// drawn with its origin in the top left (the "normal" painting direction for
  /// images); and in [TextDirection.rtl] contexts, the image will be drawn with
  /// a scaling factor of -1 in the horizontal direction so that the origin is
  /// in the top right.
  final bool matchTextDirection;

143 144
  /// Defines image pixels to be shown per logical pixels.
  ///
145
  /// By default the value of scale is 1.0. The scale for the image is
146 147 148
  /// calculated by multiplying [scale] with `scale` of the given [ImageProvider].
  final double scale;

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  /// If non-null, the value is multiplied with the opacity of each image
  /// pixel before painting onto the canvas.
  ///
  /// This is more efficient than using [Opacity] or [FadeTransition] to
  /// change the opacity of an image.
  final double opacity;

  /// Used to set the filterQuality of the image.
  ///
  /// Use the "low" quality setting to scale the image, which corresponds to
  /// bilinear interpolation, rather than the default "none" which corresponds
  /// to nearest-neighbor.
  final FilterQuality filterQuality;

  /// Whether the colors of the image are inverted when drawn.
  ///
  /// Inverting the colors of an image applies a new color filter to the paint.
  /// If there is another specified color filter, the invert will be applied
  /// after it. This is primarily used for implementing smart invert on iOS.
  ///
  /// See also:
  ///
  ///  * [Paint.invertColors], for the dart:ui implementation.
  final bool invertColors;

  /// Whether to paint the image with anti-aliasing.
  ///
  /// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
  final bool isAntiAlias;

179 180 181 182 183 184 185
  /// Creates a [DecorationImagePainter] for this [DecorationImage].
  ///
  /// The `onChanged` argument must not be null. It will be called whenever the
  /// image needs to be repainted, e.g. because it is loading incrementally or
  /// because it is animated.
  DecorationImagePainter createPainter(VoidCallback onChanged) {
    assert(onChanged != null);
186
    return DecorationImagePainter._(this, onChanged);
187 188
  }

189
  @override
190
  bool operator ==(Object other) {
191 192
    if (identical(this, other))
      return true;
193
    if (other.runtimeType != runtimeType)
194
      return false;
195 196 197 198 199 200 201
    return other is DecorationImage
        && other.image == image
        && other.colorFilter == colorFilter
        && other.fit == fit
        && other.alignment == alignment
        && other.centerSlice == centerSlice
        && other.repeat == repeat
202
        && other.matchTextDirection == matchTextDirection
203 204 205 206 207
        && other.scale == scale
        && other.opacity == opacity
        && other.filterQuality == filterQuality
        && other.invertColors == invertColors
        && other.isAntiAlias == isAntiAlias;
208 209 210
  }

  @override
211 212 213 214 215 216 217 218 219 220 221 222 223 224
  int get hashCode => hashValues(
    image,
    colorFilter,
    fit,
    alignment,
    centerSlice,
    repeat,
    matchTextDirection,
    scale,
    opacity,
    filterQuality,
    invertColors,
    isAntiAlias,
  );
225 226 227

  @override
  String toString() {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    final List<String> properties = <String>[
      '$image',
      if (colorFilter != null)
        '$colorFilter',
      if (fit != null &&
          !(fit == BoxFit.fill && centerSlice != null) &&
          !(fit == BoxFit.scaleDown && centerSlice == null))
        '$fit',
      '$alignment',
      if (centerSlice != null)
        'centerSlice: $centerSlice',
      if (repeat != ImageRepeat.noRepeat)
        '$repeat',
      if (matchTextDirection)
        'match text direction',
243 244 245 246 247 248 249
      'scale $scale',
      'opacity $opacity',
      '$filterQuality',
      if (invertColors)
        'invert colors',
      if (isAntiAlias)
        'use anti-aliasing',
250
    ];
251
    return '${objectRuntimeType(this, 'DecorationImage')}(${properties.join(", ")})';
252 253 254
  }
}

255 256 257 258 259 260 261 262 263 264 265 266
/// The painter for a [DecorationImage].
///
/// To obtain a painter, call [DecorationImage.createPainter].
///
/// To paint, call [paint]. The `onChanged` callback passed to
/// [DecorationImage.createPainter] will be called if the image needs to paint
/// again (e.g. because it is animated or because it had not yet loaded the
/// first time the [paint] method was called).
///
/// This object should be disposed using the [dispose] method when it is no
/// longer needed.
class DecorationImagePainter {
267
  DecorationImagePainter._(this._details, this._onChanged) : assert(_details != null);
268 269 270 271

  final DecorationImage _details;
  final VoidCallback _onChanged;

272 273
  ImageStream? _imageStream;
  ImageInfo? _image;
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288
  /// Draw the image onto the given canvas.
  ///
  /// The image is drawn at the position and size given by the `rect` argument.
  ///
  /// The image is clipped to the given `clipPath`, if any.
  ///
  /// The `configuration` object is used to resolve the image (e.g. to pick
  /// resolution-specific assets), and to implement the
  /// [DecorationImage.matchTextDirection] feature.
  ///
  /// If the image needs to be painted again, e.g. because it is animated or
  /// because it had not yet been loaded the first time this method was called,
  /// then the `onChanged` callback passed to [DecorationImage.createPainter]
  /// will be called.
289
  void paint(Canvas canvas, Rect rect, Path? clipPath, ImageConfiguration configuration) {
290 291 292 293 294 295 296 297 298 299
    assert(canvas != null);
    assert(rect != null);
    assert(configuration != null);

    bool flipHorizontally = false;
    if (_details.matchTextDirection) {
      assert(() {
        // We check this first so that the assert will fire immediately, not just
        // when the image is ready.
        if (configuration.textDirection == null) {
300
          throw FlutterError.fromParts(<DiagnosticsNode>[
301
            ErrorSummary('DecorationImage.matchTextDirection can only be used when a TextDirection is available.'),
302 303
            ErrorDescription(
              'When DecorationImagePainter.paint() was called, there was no text direction provided '
304
              'in the ImageConfiguration object to match.',
305 306 307 308
            ),
            DiagnosticsProperty<DecorationImage>('The DecorationImage was', _details, style: DiagnosticsTreeStyle.errorProperty),
            DiagnosticsProperty<ImageConfiguration>('The ImageConfiguration was', configuration, style: DiagnosticsTreeStyle.errorProperty),
          ]);
309 310 311 312 313 314 315 316 317
        }
        return true;
      }());
      if (configuration.textDirection == TextDirection.rtl)
        flipHorizontally = true;
    }

    final ImageStream newImageStream = _details.image.resolve(configuration);
    if (newImageStream.key != _imageStream?.key) {
318 319 320 321
      final ImageStreamListener listener = ImageStreamListener(
        _handleImage,
        onError: _details.onError,
      );
322
      _imageStream?.removeListener(listener);
323
      _imageStream = newImageStream;
324
      _imageStream!.addListener(listener);
325 326 327 328 329 330 331 332 333 334 335 336
    }
    if (_image == null)
      return;

    if (clipPath != null) {
      canvas.save();
      canvas.clipPath(clipPath);
    }

    paintImage(
      canvas: canvas,
      rect: rect,
337 338 339
      image: _image!.image,
      debugImageLabel: _image!.debugLabel,
      scale: _details.scale * _image!.scale,
340 341 342 343 344 345
      colorFilter: _details.colorFilter,
      fit: _details.fit,
      alignment: _details.alignment.resolve(configuration.textDirection),
      centerSlice: _details.centerSlice,
      repeat: _details.repeat,
      flipHorizontally: flipHorizontally,
346 347 348 349
      opacity: _details.opacity,
      filterQuality: _details.filterQuality,
      invertColors: _details.invertColors,
      isAntiAlias: _details.isAntiAlias,
350 351 352 353 354 355
    );

    if (clipPath != null)
      canvas.restore();
  }

356
  void _handleImage(ImageInfo value, bool synchronousCall) {
357 358
    if (_image == value)
      return;
359 360 361 362 363
    if (_image != null && _image!.isCloneOf(value)) {
      value.dispose();
      return;
    }
    _image?.dispose();
364 365 366 367 368 369 370 371 372 373 374 375 376
    _image = value;
    assert(_onChanged != null);
    if (!synchronousCall)
      _onChanged();
  }

  /// Releases the resources used by this painter.
  ///
  /// This should be called whenever the painter is no longer needed.
  ///
  /// After this method has been called, the object is no longer usable.
  @mustCallSuper
  void dispose() {
377 378 379 380
    _imageStream?.removeListener(ImageStreamListener(
      _handleImage,
      onError: _details.onError,
    ));
381 382
    _image?.dispose();
    _image = null;
383
  }
384 385 386

  @override
  String toString() {
387
    return '${objectRuntimeType(this, 'DecorationImagePainter')}(stream: $_imageStream, image: $_image) for $_details';
388
  }
389 390
}

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
/// Used by [paintImage] to report image sizes drawn at the end of the frame.
Map<String, ImageSizeInfo> _pendingImageSizeInfo = <String, ImageSizeInfo>{};

/// [ImageSizeInfo]s that were reported on the last frame.
///
/// Used to prevent duplicative reports from frame to frame.
Set<ImageSizeInfo> _lastFrameImageSizeInfo = <ImageSizeInfo>{};

/// Flushes inter-frame tracking of image size information from [paintImage].
///
/// Has no effect if asserts are disabled.
@visibleForTesting
void debugFlushLastFrameImageSizeInfo() {
  assert(() {
    _lastFrameImageSizeInfo = <ImageSizeInfo>{};
    return true;
  }());
}

410 411
/// Paints an image into the given rectangle on the canvas.
///
Ian Hickson's avatar
Ian Hickson committed
412 413
/// The arguments have the following meanings:
///
414
///  * `canvas`: The canvas onto which the image will be painted.
Ian Hickson's avatar
Ian Hickson committed
415
///
416 417 418
///  * `rect`: The region of the canvas into which the image will be painted.
///    The image might not fill the entire rectangle (e.g., depending on the
///    `fit`). If `rect` is empty, nothing is painted.
Ian Hickson's avatar
Ian Hickson committed
419
///
420
///  * `image`: The image to paint onto the canvas.
Ian Hickson's avatar
Ian Hickson committed
421
///
422 423
///  * `scale`: The number of image pixels for each logical pixel.
///
424 425
///  * `opacity`: The opacity to paint the image onto the canvas with.
///
426 427
///  * `colorFilter`: If non-null, the color filter to apply when painting the
///    image.
Ian Hickson's avatar
Ian Hickson committed
428
///
429 430 431 432 433
///  * `fit`: How the image should be inscribed into `rect`. If null, the
///    default behavior depends on `centerSlice`. If `centerSlice` is also null,
///    the default behavior is [BoxFit.scaleDown]. If `centerSlice` is
///    non-null, the default behavior is [BoxFit.fill]. See [BoxFit] for
///    details.
Ian Hickson's avatar
Ian Hickson committed
434 435 436
///
///  * `alignment`: How the destination rectangle defined by applying `fit` is
///    aligned within `rect`. For example, if `fit` is [BoxFit.contain] and
437
///    `alignment` is [Alignment.bottomRight], the image will be as large
Ian Hickson's avatar
Ian Hickson committed
438
///    as possible within `rect` and placed with its bottom right corner at the
439
///    bottom right corner of `rect`. Defaults to [Alignment.center].
Ian Hickson's avatar
Ian Hickson committed
440
///
441 442 443 444 445 446 447 448 449 450
///  * `centerSlice`: The image is drawn in nine portions described by splitting
///    the image by drawing two horizontal lines and two vertical lines, where
///    `centerSlice` describes the rectangle formed by the four points where
///    these four lines intersect each other. (This forms a 3-by-3 grid
///    of regions, the center region being described by `centerSlice`.)
///    The four regions in the corners are drawn, without scaling, in the four
///    corners of the destination rectangle defined by applying `fit`. The
///    remaining five regions are drawn by stretching them to fit such that they
///    exactly cover the destination rectangle while maintaining their relative
///    positions.
Ian Hickson's avatar
Ian Hickson committed
451 452 453 454 455 456 457 458 459 460 461
///
///  * `repeat`: If the image does not fill `rect`, whether and how the image
///    should be repeated to fill `rect`. By default, the image is not repeated.
///    See [ImageRepeat] for details.
///
///  * `flipHorizontally`: Whether to flip the image horizontally. This is
///    occasionally used with images in right-to-left environments, for images
///    that were designed for left-to-right locales (or vice versa). Be careful,
///    when using this, to not flip images with integral shadows, text, or other
///    effects that will look incorrect when flipped.
///
462 463 464 465 466
///  * `invertColors`: Inverting the colors of an image applies a new color
///    filter to the paint. If there is another specified color filter, the
///    invert will be applied after it. This is primarily used for implementing
///    smart invert on iOS.
///
467 468 469 470 471 472
///  * `filterQuality`: Use this to change the quality when scaling an image.
///     Use the [FilterQuality.low] quality setting to scale the image, which corresponds to
///     bilinear interpolation, rather than the default [FilterQuality.none] which corresponds
///     to nearest-neighbor.
///
/// The `canvas`, `rect`, `image`, `scale`, `alignment`, `repeat`, `flipHorizontally` and `filterQuality`
Ian Hickson's avatar
Ian Hickson committed
473
/// arguments must not be null.
474 475 476 477 478 479 480
///
/// See also:
///
///  * [paintBorder], which paints a border around a rectangle on a canvas.
///  * [DecorationImage], which holds a configuration for calling this function.
///  * [BoxDecoration], which uses this function to paint a [DecorationImage].
void paintImage({
481 482 483 484
  required Canvas canvas,
  required Rect rect,
  required ui.Image image,
  String? debugImageLabel,
485
  double scale = 1.0,
486
  double opacity = 1.0,
487 488
  ColorFilter? colorFilter,
  BoxFit? fit,
489
  Alignment alignment = Alignment.center,
490
  Rect? centerSlice,
491 492
  ImageRepeat repeat = ImageRepeat.noRepeat,
  bool flipHorizontally = false,
493
  bool invertColors = false,
494
  FilterQuality filterQuality = FilterQuality.low,
495
  bool isAntiAlias = false,
496 497 498
}) {
  assert(canvas != null);
  assert(image != null);
Ian Hickson's avatar
Ian Hickson committed
499 500 501
  assert(alignment != null);
  assert(repeat != null);
  assert(flipHorizontally != null);
502
  assert(isAntiAlias != null);
503 504 505 506
  assert(
    image.debugGetOpenHandleStackTraces()?.isNotEmpty ?? true,
    'Cannot paint an image that is disposed.\n'
    'The caller of paintImage is expected to wait to dispose the image until '
507
    'after painting has completed.',
508
  );
509 510 511
  if (rect.isEmpty)
    return;
  Size outputSize = rect.size;
512
  Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
513
  Offset? sliceBorder;
514
  if (centerSlice != null) {
515
    sliceBorder = inputSize / scale - centerSlice.size as Offset;
516
    outputSize = outputSize - sliceBorder as Size;
517
    inputSize = inputSize - sliceBorder * scale as Size;
518 519 520
  }
  fit ??= centerSlice == null ? BoxFit.scaleDown : BoxFit.fill;
  assert(centerSlice == null || (fit != BoxFit.none && fit != BoxFit.cover));
521 522
  final FittedSizes fittedSizes = applyBoxFit(fit, inputSize / scale, outputSize);
  final Size sourceSize = fittedSizes.source * scale;
523 524
  Size destinationSize = fittedSizes.destination;
  if (centerSlice != null) {
525
    outputSize += sliceBorder!;
526 527 528 529 530
    destinationSize += sliceBorder;
    // We don't have the ability to draw a subset of the image at the same time
    // as we apply a nine-patch stretch.
    assert(sourceSize == inputSize, 'centerSlice was used with a BoxFit that does not guarantee that the image is fully visible.');
  }
531

532 533 534 535 536 537 538 539
  if (repeat != ImageRepeat.noRepeat && destinationSize == outputSize) {
    // There's no need to repeat the image because we're exactly filling the
    // output rect with the image.
    repeat = ImageRepeat.noRepeat;
  }
  final Paint paint = Paint()..isAntiAlias = isAntiAlias;
  if (colorFilter != null)
    paint.colorFilter = colorFilter;
540
  paint.color = Color.fromRGBO(0, 0, 0, opacity);
541
  paint.filterQuality = filterQuality;
542 543 544 545 546 547 548 549 550 551 552
  paint.invertColors = invertColors;
  final double halfWidthDelta = (outputSize.width - destinationSize.width) / 2.0;
  final double halfHeightDelta = (outputSize.height - destinationSize.height) / 2.0;
  final double dx = halfWidthDelta + (flipHorizontally ? -alignment.x : alignment.x) * halfWidthDelta;
  final double dy = halfHeightDelta + alignment.y * halfHeightDelta;
  final Offset destinationPosition = rect.topLeft.translate(dx, dy);
  final Rect destinationRect = destinationPosition & destinationSize;

  // Set to true if we added a saveLayer to the canvas to invert/flip the image.
  bool invertedCanvas = false;
  // Output size and destination rect are fully calculated.
553 554 555 556 557
  if (!kReleaseMode) {
    final ImageSizeInfo sizeInfo = ImageSizeInfo(
      // Some ImageProvider implementations may not have given this.
      source: debugImageLabel ?? '<Unknown Image(${image.width}×${image.height})>',
      imageSize: Size(image.width.toDouble(), image.height.toDouble()),
558 559
      // It's ok to use this instead of a MediaQuery because if this changes,
      // whatever is aware of the MediaQuery will be repainting the image anyway.
560
      displaySize: outputSize * PaintingBinding.instance.window.devicePixelRatio,
561
    );
562 563 564 565
    assert(() {
      if (debugInvertOversizedImages &&
          sizeInfo.decodedSizeInBytes > sizeInfo.displaySizeInBytes + debugImageOverheadAllowance) {
        final int overheadInKilobytes = (sizeInfo.decodedSizeInBytes - sizeInfo.displaySizeInBytes) ~/ 1024;
566 567
        final int outputWidth = sizeInfo.displaySize.width.toInt();
        final int outputHeight = sizeInfo.displaySize.height.toInt();
568 569 570 571
        FlutterError.reportError(FlutterErrorDetails(
          exception: 'Image $debugImageLabel has a display size of '
            '$outputWidth×$outputHeight but a decode size of '
            '${image.width}×${image.height}, which uses an additional '
572
            '${overheadInKilobytes}KB.\n\n'
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
            'Consider resizing the asset ahead of time, supplying a cacheWidth '
            'parameter of $outputWidth, a cacheHeight parameter of '
            '$outputHeight, or using a ResizeImage.',
          library: 'painting library',
          context: ErrorDescription('while painting an image'),
        ));
        // Invert the colors of the canvas.
        canvas.saveLayer(
          destinationRect,
          Paint()..colorFilter = const ColorFilter.matrix(<double>[
            -1,  0,  0, 0, 255,
             0, -1,  0, 0, 255,
             0,  0, -1, 0, 255,
             0,  0,  0, 1,   0,
          ]),
        );
        // Flip the canvas vertically.
        final double dy = -(rect.top + rect.height / 2.0);
        canvas.translate(0.0, -dy);
        canvas.scale(1.0, -1.0);
        canvas.translate(0.0, dy);
        invertedCanvas = true;
      }
      return true;
    }());
598 599
    // Avoid emitting events that are the same as those emitted in the last frame.
    if (!_lastFrameImageSizeInfo.contains(sizeInfo)) {
600
      final ImageSizeInfo? existingSizeInfo = _pendingImageSizeInfo[sizeInfo.source];
601
      if (existingSizeInfo == null || existingSizeInfo.displaySizeInBytes < sizeInfo.displaySizeInBytes) {
602
        _pendingImageSizeInfo[sizeInfo.source!] = sizeInfo;
603
      }
604
      debugOnPaintImage?.call(sizeInfo);
605
      SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
606 607 608 609 610 611
        _lastFrameImageSizeInfo = _pendingImageSizeInfo.values.toSet();
        if (_pendingImageSizeInfo.isEmpty) {
          return;
        }
        developer.postEvent(
          'Flutter.ImageSizesForFrame',
612
          <String, Object>{
613
            for (ImageSizeInfo imageSizeInfo in _pendingImageSizeInfo.values)
614
              imageSizeInfo.source!: imageSizeInfo.toJson(),
615 616 617 618 619 620 621
          },
        );
        _pendingImageSizeInfo = <String, ImageSizeInfo>{};
      });
    }
  }

622
  final bool needSave = centerSlice != null || repeat != ImageRepeat.noRepeat || flipHorizontally;
Ian Hickson's avatar
Ian Hickson committed
623
  if (needSave)
624
    canvas.save();
Ian Hickson's avatar
Ian Hickson committed
625
  if (repeat != ImageRepeat.noRepeat)
626
    canvas.clipRect(rect);
Ian Hickson's avatar
Ian Hickson committed
627 628 629 630 631
  if (flipHorizontally) {
    final double dx = -(rect.left + rect.width / 2.0);
    canvas.translate(-dx, 0.0);
    canvas.scale(-1.0, 1.0);
    canvas.translate(dx, 0.0);
632 633
  }
  if (centerSlice == null) {
Ian Hickson's avatar
Ian Hickson committed
634
    final Rect sourceRect = alignment.inscribe(
635
      sourceSize, Offset.zero & inputSize,
636
    );
637 638 639
    if (repeat == ImageRepeat.noRepeat) {
      canvas.drawImageRect(image, sourceRect, destinationRect, paint);
    } else {
640
      for (final Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat))
641 642
        canvas.drawImageRect(image, sourceRect, tileRect, paint);
    }
643
  } else {
644
    canvas.scale(1 / scale);
645
    if (repeat == ImageRepeat.noRepeat) {
646
      canvas.drawImageNine(image, _scaleRect(centerSlice, scale), _scaleRect(destinationRect, scale), paint);
647
    } else {
648
      for (final Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat))
649
        canvas.drawImageNine(image, _scaleRect(centerSlice, scale), _scaleRect(tileRect, scale), paint);
650
    }
651
  }
Ian Hickson's avatar
Ian Hickson committed
652
  if (needSave)
653
    canvas.restore();
654 655 656 657

  if (invertedCanvas) {
    canvas.restore();
  }
658 659
}

660
Iterable<Rect> _generateImageTileRects(Rect outputRect, Rect fundamentalRect, ImageRepeat repeat) {
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
  int startX = 0;
  int startY = 0;
  int stopX = 0;
  int stopY = 0;
  final double strideX = fundamentalRect.width;
  final double strideY = fundamentalRect.height;

  if (repeat == ImageRepeat.repeat || repeat == ImageRepeat.repeatX) {
    startX = ((outputRect.left - fundamentalRect.left) / strideX).floor();
    stopX = ((outputRect.right - fundamentalRect.right) / strideX).ceil();
  }

  if (repeat == ImageRepeat.repeat || repeat == ImageRepeat.repeatY) {
    startY = ((outputRect.top - fundamentalRect.top) / strideY).floor();
    stopY = ((outputRect.bottom - fundamentalRect.bottom) / strideY).ceil();
  }

678 679 680 681 682
  return <Rect>[
    for (int i = startX; i <= stopX; ++i)
      for (int j = startY; j <= stopY; ++j)
        fundamentalRect.shift(Offset(i * strideX, j * strideY)),
  ];
683
}
684 685

Rect _scaleRect(Rect rect, double scale) => Rect.fromLTRB(rect.left * scale, rect.top * scale, rect.right * scale, rect.bottom * scale);