painting.dart 204.9 KB
Newer Older
M
Michael Goderbauer 已提交
1
// Copyright 2013 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
// @dart = 2.10
6

A
Adam Barth 已提交
7
part of dart.ui;
8

9 10 11 12 13 14 15 16
// Some methods in this file assert that their arguments are not null. These
// asserts are just to improve the error messages; they should only cover
// arguments that are either dereferenced _in Dart_, before being passed to the
// engine, or that the engine explicitly null-checks itself (after attempting to
// convert the argument to a native type). It should not be possible for a null
// or invalid value to be used by the engine even in release mode, since that
// would cause a crash. It is, however, acceptable for error messages to be much
// less useful or correct in release mode than in debug mode.
17
//
18 19
// Painting APIs will also warn about arguments representing NaN coordinates,
// which can not be rendered by Skia.
20

21
// Update this list when changing the list of supported codecs.
22 23 24 25 26 27 28 29 30
/// {@template dart.ui.imageFormats}
/// JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP, and WBMP. Additional
/// formats may be supported by the underlying platform. Flutter will
/// attempt to call platform API to decode unrecognized formats, and if the
/// platform API supports decoding the image Flutter will be able to render it.
/// {@endtemplate}

// TODO(gspencergoog): remove this template block once the framework templates
// are renamed to not reference it.
31
/// {@template flutter.dart:ui.imageFormats}
32 33 34 35
/// JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP, and WBMP. Additional
/// formats may be supported by the underlying platform. Flutter will
/// attempt to call platform API to decode unrecognized formats, and if the
/// platform API supports decoding the image Flutter will be able to render it.
36 37
/// {@endtemplate}

38
bool _rectIsValid(Rect rect) {
39
  assert(rect != null, 'Rect argument was null.'); // ignore: unnecessary_null_comparison
D
Dan Field 已提交
40
  assert(!rect.hasNaN, 'Rect argument contained a NaN value.');
41
  return true;
42 43 44
}

bool _rrectIsValid(RRect rrect) {
45
  assert(rrect != null, 'RRect argument was null.'); // ignore: unnecessary_null_comparison
D
Dan Field 已提交
46
  assert(!rrect.hasNaN, 'RRect argument contained a NaN value.');
47
  return true;
48 49 50
}

bool _offsetIsValid(Offset offset) {
51
  assert(offset != null, 'Offset argument was null.'); // ignore: unnecessary_null_comparison
52 53
  assert(!offset.dx.isNaN && !offset.dy.isNaN, 'Offset argument contained a NaN value.');
  return true;
54
}
55

56
bool _matrix4IsValid(Float64List matrix4) {
57
  assert(matrix4 != null, 'Matrix4 argument was null.'); // ignore: unnecessary_null_comparison
58
  assert(matrix4.length == 16, 'Matrix4 must have 16 entries.');
59
  assert(matrix4.every((double value) => value.isFinite), 'Matrix4 entries must be finite.');
60 61 62
  return true;
}

63
bool _radiusIsValid(Radius radius) {
64
  assert(radius != null, 'Radius argument was null.'); // ignore: unnecessary_null_comparison
65 66 67 68
  assert(!radius.x.isNaN && !radius.y.isNaN, 'Radius argument contained a NaN value.');
  return true;
}

69
Color _scaleAlpha(Color a, double factor) {
70
  return a.withAlpha((a.alpha * factor).round().clamp(0, 255));
71 72
}

I
Ian Hickson 已提交
73 74 75 76
/// An immutable 32 bit color value in ARGB format.
///
/// Consider the light teal of the Flutter logo. It is fully opaque, with a red
/// channel value of 0x42 (66), a green channel value of 0xA5 (165), and a blue
77
/// channel value of 0xF5 (245). In the common "hash syntax" for color values,
I
Ian Hickson 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
/// it would be described as `#42A5F5`.
///
/// Here are some ways it could be constructed:
///
/// ```dart
/// Color c = const Color(0xFF42A5F5);
/// Color c = const Color.fromARGB(0xFF, 0x42, 0xA5, 0xF5);
/// Color c = const Color.fromARGB(255, 66, 165, 245);
/// Color c = const Color.fromRGBO(66, 165, 245, 1.0);
/// ```
///
/// If you are having a problem with `Color` wherein it seems your color is just
/// not painting, check to make sure you are specifying the full 8 hexadecimal
/// digits. If you only specify six, then the leading two digits are assumed to
/// be zero, which means fully-transparent:
///
/// ```dart
/// Color c1 = const Color(0xFFFFFF); // fully transparent white (invisible)
/// Color c2 = const Color(0xFFFFFFFF); // fully opaque white (visible)
/// ```
S
Seth Ladd 已提交
98 99 100 101 102
///
/// See also:
///
///  * [Colors](https://docs.flutter.io/flutter/material/Colors-class.html), which
///    defines the colors found in the Material Design specification.
103
class Color {
I
Ian Hickson 已提交
104
  /// Construct a color from the lower 32 bits of an [int].
105
  ///
I
Ian Hickson 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119
  /// The bits are interpreted as follows:
  ///
  /// * Bits 24-31 are the alpha value.
  /// * Bits 16-23 are the red value.
  /// * Bits 8-15 are the green value.
  /// * Bits 0-7 are the blue value.
  ///
  /// In other words, if AA is the alpha value in hex, RR the red value in hex,
  /// GG the green value in hex, and BB the blue value in hex, a color can be
  /// expressed as `const Color(0xAARRGGBB)`.
  ///
  /// For example, to get a fully opaque orange, you would use `const
  /// Color(0xFFFF9000)` (`FF` for the alpha, `FF` for the red, `90` for the
  /// green, and `00` for the blue).
120
  @pragma('vm:entry-point')
121
  const Color(int value) : value = value & 0xFFFFFFFF;
122 123

  /// Construct a color from the lower 8 bits of four integers.
A
Adam Barth 已提交
124 125 126 127
  ///
  /// * `a` is the alpha value, with 0 being transparent and 255 being fully
  ///   opaque.
  /// * `r` is [red], from 0 to 255.
128 129
  /// * `g` is [green], from 0 to 255.
  /// * `b` is [blue], from 0 to 255.
A
Adam Barth 已提交
130 131 132
  ///
  /// Out of range values are brought into range using modulo 255.
  ///
133
  /// See also [fromRGBO], which takes the alpha value as a floating point
A
Adam Barth 已提交
134
  /// value.
135
  const Color.fromARGB(int a, int r, int g, int b) :
136 137 138 139
    value = (((a & 0xff) << 24) |
             ((r & 0xff) << 16) |
             ((g & 0xff) << 8)  |
             ((b & 0xff) << 0)) & 0xFFFFFFFF;
140

A
Adam Barth 已提交
141 142 143
  /// Create a color from red, green, blue, and opacity, similar to `rgba()` in CSS.
  ///
  /// * `r` is [red], from 0 to 255.
144 145
  /// * `g` is [green], from 0 to 255.
  /// * `b` is [blue], from 0 to 255.
146
  /// * `opacity` is alpha channel of this color as a double, with 0.0 being
A
Adam Barth 已提交
147 148 149 150 151
  ///   transparent and 1.0 being fully opaque.
  ///
  /// Out of range values are brought into range using modulo 255.
  ///
  /// See also [fromARGB], which takes the opacity as an integer value.
152
  const Color.fromRGBO(int r, int g, int b, double opacity) :
153 154 155 156
    value = ((((opacity * 0xff ~/ 1) & 0xff) << 24) |
              ((r                    & 0xff) << 16) |
              ((g                    & 0xff) << 8)  |
              ((b                    & 0xff) << 0)) & 0xFFFFFFFF;
A
Adam Barth 已提交
157

158 159
  /// A 32 bit value representing this color.
  ///
I
Ian Hickson 已提交
160 161 162 163 164 165
  /// The bits are assigned as follows:
  ///
  /// * Bits 24-31 are the alpha value.
  /// * Bits 16-23 are the red value.
  /// * Bits 8-15 are the green value.
  /// * Bits 0-7 are the blue value.
166
  final int value;
167 168

  /// The alpha channel of this color in an 8 bit value.
A
Adam Barth 已提交
169 170 171
  ///
  /// A value of 0 means this color is fully transparent. A value of 255 means
  /// this color is fully opaque.
172
  int get alpha => (0xff000000 & value) >> 24;
173 174

  /// The alpha channel of this color as a double.
A
Adam Barth 已提交
175 176 177
  ///
  /// A value of 0.0 means this color is fully transparent. A value of 1.0 means
  /// this color is fully opaque.
178
  double get opacity => alpha / 0xFF;
179 180

  /// The red channel of this color in an 8 bit value.
181
  int get red => (0x00ff0000 & value) >> 16;
182 183

  /// The green channel of this color in an 8 bit value.
184
  int get green => (0x0000ff00 & value) >> 8;
185 186

  /// The blue channel of this color in an 8 bit value.
187
  int get blue => (0x000000ff & value) >> 0;
188 189

  /// Returns a new color that matches this color with the alpha channel
I
Ian Hickson 已提交
190
  /// replaced with `a` (which ranges from 0 to 255).
191 192
  ///
  /// Out of range values will have unexpected effects.
193
  Color withAlpha(int a) {
D
Dan Field 已提交
194
    return Color.fromARGB(a, red, green, blue);
195 196 197
  }

  /// Returns a new color that matches this color with the alpha channel
I
Ian Hickson 已提交
198
  /// replaced with the given `opacity` (which ranges from 0.0 to 1.0).
199 200
  ///
  /// Out of range values will have unexpected effects.
201
  Color withOpacity(double opacity) {
202 203 204 205 206
    assert(opacity >= 0.0 && opacity <= 1.0);
    return withAlpha((255.0 * opacity).round());
  }

  /// Returns a new color that matches this color with the red channel replaced
207 208 209
  /// with `r` (which ranges from 0 to 255).
  ///
  /// Out of range values will have unexpected effects.
210
  Color withRed(int r) {
D
Dan Field 已提交
211
    return Color.fromARGB(alpha, r, green, blue);
212 213 214
  }

  /// Returns a new color that matches this color with the green channel
215 216 217
  /// replaced with `g` (which ranges from 0 to 255).
  ///
  /// Out of range values will have unexpected effects.
218
  Color withGreen(int g) {
D
Dan Field 已提交
219
    return Color.fromARGB(alpha, red, g, blue);
220 221 222
  }

  /// Returns a new color that matches this color with the blue channel replaced
223 224 225
  /// with `b` (which ranges from 0 to 255).
  ///
  /// Out of range values will have unexpected effects.
226
  Color withBlue(int b) {
D
Dan Field 已提交
227
    return Color.fromARGB(alpha, red, green, b);
228 229
  }

X
xster 已提交
230 231 232 233
  // See <https://www.w3.org/TR/WCAG20/#relativeluminancedef>
  static double _linearizeColorComponent(double component) {
    if (component <= 0.03928)
      return component / 12.92;
234
    return math.pow((component + 0.055) / 1.055, 2.4) as double;
X
xster 已提交
235 236 237 238 239 240 241 242
  }

  /// Returns a brightness value between 0 for darkest and 1 for lightest.
  ///
  /// Represents the relative luminance of the color. This value is computationally
  /// expensive to calculate.
  ///
  /// See <https://en.wikipedia.org/wiki/Relative_luminance>.
243
  double computeLuminance() {
X
xster 已提交
244 245 246 247 248 249 250
    // See <https://www.w3.org/TR/WCAG20/#relativeluminancedef>
    final double R = _linearizeColorComponent(red / 0xFF);
    final double G = _linearizeColorComponent(green / 0xFF);
    final double B = _linearizeColorComponent(blue / 0xFF);
    return 0.2126 * R + 0.7152 * G + 0.0722 * B;
  }

I
Ian Hickson 已提交
251
  /// Linearly interpolate between two colors.
252
  ///
253 254 255
  /// This is intended to be fast but as a result may be ugly. Consider
  /// [HSVColor] or writing custom logic for interpolating colors.
  ///
256
  /// If either color is null, this function linearly interpolates from a
257
  /// transparent instance of the other color. This is usually preferable to
258 259
  /// interpolating from [material.Colors.transparent] (`const
  /// Color(0x00000000)`), which is specifically transparent _black_.
260
  ///
261 262 263 264 265 266 267 268 269
  /// The `t` argument represents position on the timeline, with 0.0 meaning
  /// that the interpolation has not started, returning `a` (or something
  /// equivalent to `a`), 1.0 meaning that the interpolation has finished,
  /// returning `b` (or something equivalent to `b`), and values in between
  /// meaning that the interpolation is at the relevant point on the timeline
  /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
  /// 1.0, so negative values and values greater than 1.0 are valid (and can
  /// easily be generated by curves such as [Curves.elasticInOut]). Each channel
  /// will be clamped to the range 0 to 255.
270
  ///
271 272
  /// Values for `t` are usually obtained from an [Animation<double>], such as
  /// an [AnimationController].
273 274
  static Color? lerp(Color? a, Color? b, double t) {
    assert(t != null); // ignore: unnecessary_null_comparison
Y
Yegor 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    if (b == null) {
      if (a == null) {
        return null;
      } else {
        return _scaleAlpha(a, 1.0 - t);
      }
    } else {
      if (a == null) {
        return _scaleAlpha(b, t);
      } else {
        return Color.fromARGB(
          _clampInt(_lerpInt(a.alpha, b.alpha, t).toInt(), 0, 255),
          _clampInt(_lerpInt(a.red, b.red, t).toInt(), 0, 255),
          _clampInt(_lerpInt(a.green, b.green, t).toInt(), 0, 255),
          _clampInt(_lerpInt(a.blue, b.blue, t).toInt(), 0, 255),
        );
      }
    }
293 294
  }

G
Greg Spencer 已提交
295 296 297 298 299 300 301 302
  /// Combine the foreground color as a transparent color over top
  /// of a background color, and return the resulting combined color.
  ///
  /// This uses standard alpha blending ("SRC over DST") rules to produce a
  /// blended color from two colors. This can be used as a performance
  /// enhancement when trying to avoid needless alpha blending compositing
  /// operations for two things that are solid colors with the same shape, but
  /// overlay each other: instead, just paint one with the combined color.
303
  static Color alphaBlend(Color foreground, Color background) {
G
Greg Spencer 已提交
304 305 306 307 308 309 310
    final int alpha = foreground.alpha;
    if (alpha == 0x00) { // Foreground completely transparent.
      return background;
    }
    final int invAlpha = 0xff - alpha;
    int backAlpha = background.alpha;
    if (backAlpha == 0xff) { // Opaque background case
D
Dan Field 已提交
311
      return Color.fromARGB(
G
Greg Spencer 已提交
312 313 314 315 316 317 318 319 320
        0xff,
        (alpha * foreground.red + invAlpha * background.red) ~/ 0xff,
        (alpha * foreground.green + invAlpha * background.green) ~/ 0xff,
        (alpha * foreground.blue + invAlpha * background.blue) ~/ 0xff,
      );
    } else { // General case
      backAlpha = (backAlpha * invAlpha) ~/ 0xff;
      final int outAlpha = alpha + backAlpha;
      assert(outAlpha != 0x00);
D
Dan Field 已提交
321
      return Color.fromARGB(
G
Greg Spencer 已提交
322 323 324 325 326 327 328 329
        outAlpha,
        (foreground.red * alpha + background.red * backAlpha) ~/ outAlpha,
        (foreground.green * alpha + background.green * backAlpha) ~/ outAlpha,
        (foreground.blue * alpha + background.blue * backAlpha) ~/ outAlpha,
      );
    }
  }

330 331 332
  /// Returns an alpha value representative of the provided [opacity] value.
  ///
  /// The [opacity] value may not be null.
333 334
  static int getAlphaFromOpacity(double opacity) {
    assert(opacity != null); // ignore: unnecessary_null_comparison
335 336 337
    return (opacity.clamp(0.0, 1.0) * 255).round();
  }

338
  @override
A
Alexandre Ardhuin 已提交
339
  bool operator ==(Object other) {
340 341 342
    if (identical(this, other))
      return true;
    if (other.runtimeType != runtimeType)
343
      return false;
344 345
    return other is Color
        && other.value == value;
346 347 348
  }

  @override
349
  int get hashCode => value.hashCode;
350 351

  @override
352
  String toString() => 'Color(0x${value.toRadixString(16).padLeft(8, '0')})';
353 354 355 356
}

/// Algorithms to use when painting on the canvas.
///
357 358 359
/// When drawing a shape or image onto a canvas, different algorithms can be
/// used to blend the pixels. The different values of [BlendMode] specify
/// different such algorithms.
360
///
361 362 363 364 365 366 367
/// Each algorithm has two inputs, the _source_, which is the image being drawn,
/// and the _destination_, which is the image into which the source image is
/// being composited. The destination is often thought of as the _background_.
/// The source and destination both have four color channels, the red, green,
/// blue, and alpha channels. These are typically represented as numbers in the
/// range 0.0 to 1.0. The output of the algorithm also has these same four
/// channels, with values computed from the source and destination.
368
///
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
/// The documentation of each value below describes how the algorithm works. In
/// each case, an image shows the output of blending a source image with a
/// destination image. In the images below, the destination is represented by an
/// image with horizontal lines and an opaque landscape photograph, and the
/// source is represented by an image with vertical lines (the same lines but
/// rotated) and a bird clip-art image. The [src] mode shows only the source
/// image, and the [dst] mode shows only the destination image. In the
/// documentation below, the transparency is illustrated by a checkerboard
/// pattern. The [clear] mode drops both the source and destination, resulting
/// in an output that is entirely transparent (illustrated by a solid
/// checkerboard pattern).
///
/// The horizontal and vertical bars in these images show the red, green, and
/// blue channels with varying opacity levels, then all three color channels
/// together with those same varying opacity levels, then all three color
G
Greg Spencer 已提交
384
/// channels set to zero with those varying opacity levels, then two bars showing
385 386 387 388 389
/// a red/green/blue repeating gradient, the first with full opacity and the
/// second with partial opacity, and finally a bar with the three color channels
/// set to zero but the opacity varying in a repeating gradient.
///
/// ## Application to the [Canvas] API
390
///
391 392 393 394
/// When using [Canvas.saveLayer] and [Canvas.restore], the blend mode of the
/// [Paint] given to the [Canvas.saveLayer] will be applied when
/// [Canvas.restore] is called. Each call to [Canvas.saveLayer] introduces a new
/// layer onto which shapes and images are painted; when [Canvas.restore] is
395 396
/// called, that layer is then composited onto the parent layer, with the source
/// being the most-recently-drawn shapes and images, and the destination being
397 398
/// the parent layer. (For the first [Canvas.saveLayer] call, the parent layer
/// is the canvas itself.)
399 400 401 402 403
///
/// See also:
///
///  * [Paint.blendMode], which uses [BlendMode] to define the compositing
///    strategy.
404
enum BlendMode {
405 406 407 408
  // This list comes from Skia's SkXfermode.h and the values (order) should be
  // kept in sync.
  // See: https://skia.org/user/api/skpaint#SkXfermode

409 410 411
  /// Drop both the source and destination images, leaving nothing.
  ///
  /// This corresponds to the "clear" Porter-Duff operator.
412
  ///
413
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_clear.png)
414
  clear,
415 416 417 418 419 420 421

  /// Drop the destination image, only paint the source image.
  ///
  /// Conceptually, the destination is first cleared, then the source image is
  /// painted.
  ///
  /// This corresponds to the "Copy" Porter-Duff operator.
422
  ///
423
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_src.png)
424
  src,
425 426 427 428 429 430 431

  /// Drop the source image, only paint the destination image.
  ///
  /// Conceptually, the source image is discarded, leaving the destination
  /// untouched.
  ///
  /// This corresponds to the "Destination" Porter-Duff operator.
432
  ///
433
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dst.png)
434
  dst,
435 436 437 438 439 440 441 442 443

  /// Composite the source image over the destination image.
  ///
  /// This is the default value. It represents the most intuitive case, where
  /// shapes are painted on top of what is below, with transparent areas showing
  /// the destination layer.
  ///
  /// This corresponds to the "Source over Destination" Porter-Duff operator,
  /// also known as the Painter's Algorithm.
444
  ///
445
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_srcOver.png)
446
  srcOver,
447 448 449 450 451 452

  /// Composite the source image under the destination image.
  ///
  /// This is the opposite of [srcOver].
  ///
  /// This corresponds to the "Destination over Source" Porter-Duff operator.
453
  ///
454
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dstOver.png)
455 456 457
  ///
  /// This is useful when the source image should have been painted before the
  /// destination image, but could not be.
458
  dstOver,
459 460

  /// Show the source image, but only where the two images overlap. The
461 462 463
  /// destination image is not rendered, it is treated merely as a mask. The
  /// color channels of the destination are ignored, only the opacity has an
  /// effect.
464 465 466 467 468 469 470 471
  ///
  /// To show the destination image instead, consider [dstIn].
  ///
  /// To reverse the semantic of the mask (only showing the source where the
  /// destination is absent, rather than where it is present), consider
  /// [srcOut].
  ///
  /// This corresponds to the "Source in Destination" Porter-Duff operator.
472
  ///
473
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_srcIn.png)
474
  srcIn,
475 476

  /// Show the destination image, but only where the two images overlap. The
477 478
  /// source image is not rendered, it is treated merely as a mask. The color
  /// channels of the source are ignored, only the opacity has an effect.
479 480 481 482
  ///
  /// To show the source image instead, consider [srcIn].
  ///
  /// To reverse the semantic of the mask (only showing the source where the
483
  /// destination is present, rather than where it is absent), consider [dstOut].
484 485
  ///
  /// This corresponds to the "Destination in Source" Porter-Duff operator.
486
  ///
487
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dstIn.png)
488
  dstIn,
489 490

  /// Show the source image, but only where the two images do not overlap. The
491 492
  /// destination image is not rendered, it is treated merely as a mask. The color
  /// channels of the destination are ignored, only the opacity has an effect.
493 494 495 496 497 498 499
  ///
  /// To show the destination image instead, consider [dstOut].
  ///
  /// To reverse the semantic of the mask (only showing the source where the
  /// destination is present, rather than where it is absent), consider [srcIn].
  ///
  /// This corresponds to the "Source out Destination" Porter-Duff operator.
500
  ///
501
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_srcOut.png)
502
  srcOut,
503 504

  /// Show the destination image, but only where the two images do not overlap. The
505 506
  /// source image is not rendered, it is treated merely as a mask. The color
  /// channels of the source are ignored, only the opacity has an effect.
507 508 509 510 511 512 513
  ///
  /// To show the source image instead, consider [srcOut].
  ///
  /// To reverse the semantic of the mask (only showing the destination where the
  /// source is present, rather than where it is absent), consider [dstIn].
  ///
  /// This corresponds to the "Destination out Source" Porter-Duff operator.
514
  ///
515
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dstOut.png)
516
  dstOut,
517 518 519 520 521

  /// Composite the source image over the destination image, but only where it
  /// overlaps the destination.
  ///
  /// This corresponds to the "Source atop Destination" Porter-Duff operator.
522 523 524 525 526 527 528 529
  ///
  /// This is essentially the [srcOver] operator, but with the output's opacity
  /// channel being set to that of the destination image instead of being a
  /// combination of both image's opacity channels.
  ///
  /// For a variant with the destination on top instead of the source, see
  /// [dstATop].
  ///
530
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_srcATop.png)
531
  srcATop,
532 533 534 535 536

  /// Composite the destination image over the source image, but only where it
  /// overlaps the source.
  ///
  /// This corresponds to the "Destination atop Source" Porter-Duff operator.
537 538 539 540 541 542 543 544
  ///
  /// This is essentially the [dstOver] operator, but with the output's opacity
  /// channel being set to that of the source image instead of being a
  /// combination of both image's opacity channels.
  ///
  /// For a variant with the source on top instead of the destination, see
  /// [srcATop].
  ///
545
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dstATop.png)
546
  dstATop,
547

548 549
  /// Apply a bitwise `xor` operator to the source and destination images. This
  /// leaves transparency where they would overlap.
550 551
  ///
  /// This corresponds to the "Source xor Destination" Porter-Duff operator.
552
  ///
553
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_xor.png)
554
  xor,
555

556 557 558 559 560
  /// Sum the components of the source and destination images.
  ///
  /// Transparency in a pixel of one of the images reduces the contribution of
  /// that image to the corresponding output pixel, as if the color of that
  /// pixel in that image was darker.
561 562
  ///
  /// This corresponds to the "Source plus Destination" Porter-Duff operator.
563
  ///
564
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_plus.png)
565
  plus,
566

567 568 569 570 571 572 573 574 575 576
  /// Multiply the color components of the source and destination images.
  ///
  /// This can only result in the same or darker colors (multiplying by white,
  /// 1.0, results in no change; multiplying by black, 0.0, results in black).
  ///
  /// When compositing two opaque images, this has similar effect to overlapping
  /// two transparencies on a projector.
  ///
  /// For a variant that also multiplies the alpha channel, consider [multiply].
  ///
577
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_modulate.png)
578 579 580
  ///
  /// See also:
  ///
G
Greg Spencer 已提交
581
  ///  * [screen], which does a similar computation but inverted.
582 583 584 585
  ///  * [overlay], which combines [modulate] and [screen] to favor the
  ///    destination image.
  ///  * [hardLight], which combines [modulate] and [screen] to favor the
  ///    source image.
586 587 588 589
  modulate,

  // Following blend modes are defined in the CSS Compositing standard.

590 591 592
  /// Multiply the inverse of the components of the source and destination
  /// images, and inverse the result.
  ///
G
Greg Spencer 已提交
593
  /// Inverting the components means that a fully saturated channel (opaque
594 595 596 597
  /// white) is treated as the value 0.0, and values normally treated as 0.0
  /// (black, transparent) are treated as 1.0.
  ///
  /// This is essentially the same as [modulate] blend mode, but with the values
G
Greg Spencer 已提交
598 599
  /// of the colors inverted before the multiplication and the result being
  /// inverted back before rendering.
600 601 602 603 604 605 606 607
  ///
  /// This can only result in the same or lighter colors (multiplying by black,
  /// 1.0, results in no change; multiplying by white, 0.0, results in white).
  /// Similarly, in the alpha channel, it can only result in more opaque colors.
  ///
  /// This has similar effect to two projectors displaying their images on the
  /// same screen simultaneously.
  ///
608
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_screen.png)
609 610 611
  ///
  /// See also:
  ///
G
Greg Spencer 已提交
612
  ///  * [modulate], which does a similar computation but without inverting the
613 614 615 616 617
  ///    values.
  ///  * [overlay], which combines [modulate] and [screen] to favor the
  ///    destination image.
  ///  * [hardLight], which combines [modulate] and [screen] to favor the
  ///    source image.
618 619
  screen,  // The last coeff mode.

620 621 622 623 624 625
  /// Multiply the components of the source and destination images after
  /// adjusting them to favor the destination.
  ///
  /// Specifically, if the destination value is smaller, this multiplies it with
  /// the source value, whereas is the source value is smaller, it multiplies
  /// the inverse of the source value with the inverse of the destination value,
G
Greg Spencer 已提交
626
  /// then inverts the result.
627
  ///
G
Greg Spencer 已提交
628
  /// Inverting the components means that a fully saturated channel (opaque
629 630 631
  /// white) is treated as the value 0.0, and values normally treated as 0.0
  /// (black, transparent) are treated as 1.0.
  ///
632
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_overlay.png)
633 634 635 636 637 638 639
  ///
  /// See also:
  ///
  ///  * [modulate], which always multiplies the values.
  ///  * [screen], which always multiplies the inverses of the values.
  ///  * [hardLight], which is similar to [overlay] but favors the source image
  ///    instead of the destination image.
640
  overlay,
641 642 643 644 645 646 647

  /// Composite the source and destination image by choosing the lowest value
  /// from each color channel.
  ///
  /// The opacity of the output image is computed in the same way as for
  /// [srcOver].
  ///
648
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_darken.png)
649
  darken,
650 651 652 653 654 655 656

  /// Composite the source and destination image by choosing the highest value
  /// from each color channel.
  ///
  /// The opacity of the output image is computed in the same way as for
  /// [srcOver].
  ///
657
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_lighten.png)
658
  lighten,
659 660 661

  /// Divide the destination by the inverse of the source.
  ///
G
Greg Spencer 已提交
662
  /// Inverting the components means that a fully saturated channel (opaque
663 664 665
  /// white) is treated as the value 0.0, and values normally treated as 0.0
  /// (black, transparent) are treated as 1.0.
  ///
666
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_colorDodge.png)
667
  colorDodge,
668

D
Dan Field 已提交
669
  /// Divide the inverse of the destination by the source, and inverse the result.
670
  ///
G
Greg Spencer 已提交
671
  /// Inverting the components means that a fully saturated channel (opaque
672 673 674
  /// white) is treated as the value 0.0, and values normally treated as 0.0
  /// (black, transparent) are treated as 1.0.
  ///
675
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_colorBurn.png)
676
  colorBurn,
677 678 679 680 681 682 683

  /// Multiply the components of the source and destination images after
  /// adjusting them to favor the source.
  ///
  /// Specifically, if the source value is smaller, this multiplies it with the
  /// destination value, whereas is the destination value is smaller, it
  /// multiplies the inverse of the destination value with the inverse of the
G
Greg Spencer 已提交
684
  /// source value, then inverts the result.
685
  ///
G
Greg Spencer 已提交
686
  /// Inverting the components means that a fully saturated channel (opaque
687 688 689
  /// white) is treated as the value 0.0, and values normally treated as 0.0
  /// (black, transparent) are treated as 1.0.
  ///
690
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_hardLight.png)
691 692 693 694 695 696 697
  ///
  /// See also:
  ///
  ///  * [modulate], which always multiplies the values.
  ///  * [screen], which always multiplies the inverses of the values.
  ///  * [overlay], which is similar to [hardLight] but favors the destination
  ///    image instead of the source image.
698
  hardLight,
699 700 701 702

  /// Use [colorDodge] for source values below 0.5 and [colorBurn] for source
  /// values above 0.5.
  ///
G
Greg Spencer 已提交
703
  /// This results in a similar but softer effect than [overlay].
704
  ///
705
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_softLight.png)
706 707 708 709
  ///
  /// See also:
  ///
  ///  * [color], which is a more subtle tinting effect.
710
  softLight,
711 712 713

  /// Subtract the smaller value from the bigger value for each channel.
  ///
G
Greg Spencer 已提交
714
  /// Compositing black has no effect; compositing white inverts the colors of
715 716 717 718 719 720 721
  /// the other image.
  ///
  /// The opacity of the output image is computed in the same way as for
  /// [srcOver].
  ///
  /// The effect is similar to [exclusion] but harsher.
  ///
722
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_difference.png)
723
  difference,
724 725 726 727

  /// Subtract double the product of the two images from the sum of the two
  /// images.
  ///
G
Greg Spencer 已提交
728
  /// Compositing black has no effect; compositing white inverts the colors of
729 730 731 732 733 734 735
  /// the other image.
  ///
  /// The opacity of the output image is computed in the same way as for
  /// [srcOver].
  ///
  /// The effect is similar to [difference] but softer.
  ///
736
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_exclusion.png)
737
  exclusion,
738 739 740 741 742 743 744 745 746 747 748 749 750 751

  /// Multiply the components of the source and destination images, including
  /// the alpha channel.
  ///
  /// This can only result in the same or darker colors (multiplying by white,
  /// 1.0, results in no change; multiplying by black, 0.0, results in black).
  ///
  /// Since the alpha channel is also multiplied, a fully-transparent pixel
  /// (opacity 0.0) in one image results in a fully transparent pixel in the
  /// output. This is similar to [dstIn], but with the colors combined.
  ///
  /// For a variant that multiplies the colors but does not multiply the alpha
  /// channel, consider [modulate].
  ///
752
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_multiply.png)
753 754
  multiply,  // The last separable mode.

755 756 757 758 759 760 761 762 763
  /// Take the hue of the source image, and the saturation and luminosity of the
  /// destination image.
  ///
  /// The effect is to tint the destination image with the source image.
  ///
  /// The opacity of the output image is computed in the same way as for
  /// [srcOver]. Regions that are entirely transparent in the source image take
  /// their hue from the destination.
  ///
764
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_hue.png)
765 766 767 768 769 770 771
  ///
  /// See also:
  ///
  ///  * [color], which is a similar but stronger effect as it also applies the
  ///    saturation of the source image.
  ///  * [HSVColor], which allows colors to be expressed using Hue rather than
  ///    the red/green/blue channels of [Color].
772
  hue,
773 774 775 776 777 778 779 780

  /// Take the saturation of the source image, and the hue and luminosity of the
  /// destination image.
  ///
  /// The opacity of the output image is computed in the same way as for
  /// [srcOver]. Regions that are entirely transparent in the source image take
  /// their saturation from the destination.
  ///
781
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_hue.png)
782 783 784 785 786 787
  ///
  /// See also:
  ///
  ///  * [color], which also applies the hue of the source image.
  ///  * [luminosity], which applies the luminosity of the source image to the
  ///    destination.
788
  saturation,
789 790 791 792 793 794 795 796 797 798

  /// Take the hue and saturation of the source image, and the luminosity of the
  /// destination image.
  ///
  /// The effect is to tint the destination image with the source image.
  ///
  /// The opacity of the output image is computed in the same way as for
  /// [srcOver]. Regions that are entirely transparent in the source image take
  /// their hue and saturation from the destination.
  ///
799
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_color.png)
800 801 802 803 804 805
  ///
  /// See also:
  ///
  ///  * [hue], which is a similar but weaker effect.
  ///  * [softLight], which is a similar tinting effect but also tints white.
  ///  * [saturation], which only applies the saturation of the source image.
806
  color,
807 808 809 810 811 812 813 814

  /// Take the luminosity of the source image, and the hue and saturation of the
  /// destination image.
  ///
  /// The opacity of the output image is computed in the same way as for
  /// [srcOver]. Regions that are entirely transparent in the source image take
  /// their luminosity from the destination.
  ///
815
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_luminosity.png)
816 817 818 819 820 821 822
  ///
  /// See also:
  ///
  ///  * [saturation], which applies the saturation of the source image to the
  ///    destination.
  ///  * [ImageFilter.blur], which can be used with [BackdropFilter] for a
  ///    related effect.
823 824 825 826 827 828 829 830 831 832 833 834
  luminosity,
}

/// Quality levels for image filters.
///
/// See [Paint.filterQuality].
enum FilterQuality {
  // This list comes from Skia's SkFilterQuality.h and the values (order) should
  // be kept in sync.

  /// Fastest possible filtering, albeit also the lowest quality.
  ///
835
  /// Typically this implies nearest-neighbor filtering.
836 837 838 839 840 841 842 843 844 845
  none,

  /// Better quality than [none], faster than [medium].
  ///
  /// Typically this implies bilinear interpolation.
  low,

  /// Better quality than [low], faster than [high].
  ///
  /// Typically this implies a combination of bilinear interpolation and
846
  /// pyramidal parametric pre-filtering (mipmaps).
847 848 849 850 851 852 853 854 855 856
  medium,

  /// Best possible quality filtering, albeit also the slowest.
  ///
  /// Typically this implies bicubic interpolation or better.
  high,
}

/// Styles to use for line endings.
///
857 858 859 860
/// See also:
///
///  * [Paint.strokeCap] for how this value is used.
///  * [StrokeJoin] for the different kinds of line segment joins.
861
// These enum values must be kept in sync with SkPaint::Cap.
862 863
enum StrokeCap {
  /// Begin and end contours with a flat edge and no extension.
864 865 866 867 868 869
  ///
  /// ![A butt cap ends line segments with a square end that stops at the end of
  /// the line segment.](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/butt_cap.png)
  ///
  /// Compare to the [square] cap, which has the same shape, but extends past
  /// the end of the line by half a stroke width.
870 871 872
  butt,

  /// Begin and end contours with a semi-circle extension.
873 874 875 876 877 878 879
  ///
  /// ![A round cap adds a rounded end to the line segment that protrudes
  /// by one half of the thickness of the line (which is the radius of the cap)
  /// past the end of the segment.](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/round_cap.png)
  ///
  /// The cap is colored in the diagram above to highlight it: in normal use it
  /// is the same color as the line.
880 881 882 883 884
  round,

  /// Begin and end contours with a half square extension. This is
  /// similar to extending each contour by half the stroke width (as
  /// given by [Paint.strokeWidth]).
885 886 887 888 889 890 891 892 893
  ///
  /// ![A square cap has a square end that effectively extends the line length
  /// by half of the stroke width.](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/square_cap.png)
  ///
  /// The cap is colored in the diagram above to highlight it: in normal use it
  /// is the same color as the line.
  ///
  /// Compare to the [butt] cap, which has the same shape, but doesn't extend
  /// past the end of the line.
894 895 896
  square,
}

897
/// Styles to use for line segment joins.
898 899 900 901
///
/// This only affects line joins for polygons drawn by [Canvas.drawPath] and
/// rectangles, not points drawn as lines with [Canvas.drawPoints].
///
902 903 904 905 906
/// See also:
///
/// * [Paint.strokeJoin] and [Paint.strokeMiterLimit] for how this value is
///   used.
/// * [StrokeCap] for the different kinds of line endings.
907 908 909
// These enum values must be kept in sync with SkPaint::Join.
enum StrokeJoin {
  /// Joins between line segments form sharp corners.
910
  ///
911
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_4_join.mp4}
912 913 914 915 916 917 918 919 920 921 922
  ///
  /// The center of the line segment is colored in the diagram above to
  /// highlight the join, but in normal usage the join is the same color as the
  /// line.
  ///
  /// See also:
  ///
  ///   * [Paint.strokeJoin], used to set the line segment join style to this
  ///     value.
  ///   * [Paint.strokeMiterLimit], used to define when a miter is drawn instead
  ///     of a bevel when the join is set to this value.
923 924 925
  miter,

  /// Joins between line segments are semi-circular.
926
  ///
927
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/round_join.mp4}
928 929 930 931 932 933 934 935 936
  ///
  /// The center of the line segment is colored in the diagram above to
  /// highlight the join, but in normal usage the join is the same color as the
  /// line.
  ///
  /// See also:
  ///
  ///   * [Paint.strokeJoin], used to set the line segment join style to this
  ///     value.
937 938 939 940
  round,

  /// Joins between line segments connect the corners of the butt ends of the
  /// line segments to give a beveled appearance.
941
  ///
942
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/bevel_join.mp4}
943 944 945 946 947 948 949 950 951
  ///
  /// The center of the line segment is colored in the diagram above to
  /// highlight the join, but in normal usage the join is the same color as the
  /// line.
  ///
  /// See also:
  ///
  ///   * [Paint.strokeJoin], used to set the line segment join style to this
  ///     value.
952 953 954
  bevel,
}

955 956 957
/// Strategies for painting shapes and paths on a canvas.
///
/// See [Paint.style].
958
// These enum values must be kept in sync with SkPaint::Style.
959 960 961 962 963
enum PaintingStyle {
  // This list comes from Skia's SkPaint.h and the values (order) should be kept
  // in sync.

  /// Apply the [Paint] to the inside of the shape. For example, when
I
Ian Hickson 已提交
964
  /// applied to the [Canvas.drawCircle] call, this results in a disc
965 966 967 968
  /// of the given size being painted.
  fill,

  /// Apply the [Paint] to the edge of the shape. For example, when
I
Ian Hickson 已提交
969
  /// applied to the [Canvas.drawCircle] call, this results is a hoop
970 971 972 973 974
  /// of the given size being painted. The line drawn on the edge will
  /// be the width given by the [Paint.strokeWidth] property.
  stroke,
}

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049

/// Different ways to clip a widget's content.
enum Clip {
  /// No clip at all.
  ///
  /// This is the default option for most widgets: if the content does not
  /// overflow the widget boundary, don't pay any performance cost for clipping.
  ///
  /// If the content does overflow, please explicitly specify the following
  /// [Clip] options:
  ///  * [hardEdge], which is the fastest clipping, but with lower fidelity.
  ///  * [antiAlias], which is a little slower than [hardEdge], but with smoothed edges.
  ///  * [antiAliasWithSaveLayer], which is much slower than [antiAlias], and should
  ///    rarely be used.
  none,

  /// Clip, but do not apply anti-aliasing.
  ///
  /// This mode enables clipping, but curves and non-axis-aligned straight lines will be
  /// jagged as no effort is made to anti-alias.
  ///
  /// Faster than other clipping modes, but slower than [none].
  ///
  /// This is a reasonable choice when clipping is needed, if the container is an axis-
  /// aligned rectangle or an axis-aligned rounded rectangle with very small corner radii.
  ///
  /// See also:
  ///
  ///  * [antiAlias], which is more reasonable when clipping is needed and the shape is not
  ///    an axis-aligned rectangle.
  hardEdge,

  /// Clip with anti-aliasing.
  ///
  /// This mode has anti-aliased clipping edges to achieve a smoother look.
  ///
  /// It' s much faster than [antiAliasWithSaveLayer], but slower than [hardEdge].
  ///
  /// This will be the common case when dealing with circles and arcs.
  ///
  /// Different from [hardEdge] and [antiAliasWithSaveLayer], this clipping may have
  /// bleeding edge artifacts.
  /// (See https://fiddle.skia.org/c/21cb4c2b2515996b537f36e7819288ae for an example.)
  ///
  /// See also:
  ///
  ///  * [hardEdge], which is a little faster, but with lower fidelity.
  ///  * [antiAliasWithSaveLayer], which is much slower, but can avoid the
  ///    bleeding edges if there's no other way.
  ///  * [Paint.isAntiAlias], which is the anti-aliasing switch for general draw operations.
  antiAlias,

  /// Clip with anti-aliasing and saveLayer immediately following the clip.
  ///
  /// This mode not only clips with anti-aliasing, but also allocates an offscreen
  /// buffer. All subsequent paints are carried out on that buffer before finally
  /// being clipped and composited back.
  ///
  /// This is very slow. It has no bleeding edge artifacts (that [antiAlias] has)
  /// but it changes the semantics as an offscreen buffer is now introduced.
  /// (See https://github.com/flutter/flutter/issues/18057#issuecomment-394197336
  /// for a difference between paint without saveLayer and paint with saveLayer.)
  ///
  /// This will be only rarely needed. One case where you might need this is if
  /// you have an image overlaid on a very different background color. In these
  /// cases, consider whether you can avoid overlaying multiple colors in one
  /// spot (e.g. by having the background color only present where the image is
  /// absent). If you can, [antiAlias] would be fine and much faster.
  ///
  /// See also:
  ///
  ///  * [antiAlias], which is much faster, and has similar clipping results.
  antiAliasWithSaveLayer,
}

1050 1051 1052 1053 1054
/// A description of the style to use when drawing on a [Canvas].
///
/// Most APIs on [Canvas] take a [Paint] object to describe the style
/// to use for that operation.
class Paint {
1055 1056 1057 1058 1059
  // Paint objects are encoded in two buffers:
  //
  // * _data is binary data in four-byte fields, each of which is either a
  //   uint32_t or a float. The default value for each field is encoded as
  //   zero to make initialization trivial. Most values already have a default
1060
  //   value of zero, but some, such as color, have a non-zero default value.
1061 1062 1063 1064 1065 1066 1067 1068
  //   To encode or decode these values, XOR the value with the default value.
  //
  // * _objects is a list of unencodable objects, typically wrappers for native
  //   objects. The objects are simply stored in the list without any additional
  //   encoding.
  //
  // The binary format must match the deserialization code in paint.cc.

D
Dan Field 已提交
1069
  final ByteData _data = ByteData(_kDataByteCount);
1070 1071
  static const int _kIsAntiAliasIndex = 0;
  static const int _kColorIndex = 1;
1072
  static const int _kBlendModeIndex = 2;
1073 1074 1075
  static const int _kStyleIndex = 3;
  static const int _kStrokeWidthIndex = 4;
  static const int _kStrokeCapIndex = 5;
1076 1077 1078
  static const int _kStrokeJoinIndex = 6;
  static const int _kStrokeMiterLimitIndex = 7;
  static const int _kFilterQualityIndex = 8;
1079 1080 1081 1082
  static const int _kMaskFilterIndex = 9;
  static const int _kMaskFilterBlurStyleIndex = 10;
  static const int _kMaskFilterSigmaIndex = 11;
  static const int _kInvertColorIndex = 12;
1083
  static const int _kDitherIndex = 13;
1084 1085 1086

  static const int _kIsAntiAliasOffset = _kIsAntiAliasIndex << 2;
  static const int _kColorOffset = _kColorIndex << 2;
1087
  static const int _kBlendModeOffset = _kBlendModeIndex << 2;
1088 1089 1090
  static const int _kStyleOffset = _kStyleIndex << 2;
  static const int _kStrokeWidthOffset = _kStrokeWidthIndex << 2;
  static const int _kStrokeCapOffset = _kStrokeCapIndex << 2;
1091 1092
  static const int _kStrokeJoinOffset = _kStrokeJoinIndex << 2;
  static const int _kStrokeMiterLimitOffset = _kStrokeMiterLimitIndex << 2;
1093
  static const int _kFilterQualityOffset = _kFilterQualityIndex << 2;
1094 1095 1096
  static const int _kMaskFilterOffset = _kMaskFilterIndex << 2;
  static const int _kMaskFilterBlurStyleOffset = _kMaskFilterBlurStyleIndex << 2;
  static const int _kMaskFilterSigmaOffset = _kMaskFilterSigmaIndex << 2;
1097
  static const int _kInvertColorOffset = _kInvertColorIndex << 2;
1098
  static const int _kDitherOffset = _kDitherIndex << 2;
1099
  // If you add more fields, remember to update _kDataByteCount.
1100
  static const int _kDataByteCount = 56;
1101 1102

  // Binary format must match the deserialization code in paint.cc.
1103 1104 1105 1106 1107 1108
  List<dynamic>? _objects;

  List<dynamic> _ensureObjectsInitialized() {
    return _objects ??= List<dynamic>.filled(_kObjectCount, null, growable: false);
  }

1109
  static const int _kShaderIndex = 0;
1110
  static const int _kColorFilterIndex = 1;
1111 1112
  static const int _kImageFilterIndex = 2;
  static const int _kObjectCount = 3; // Must be one larger than the largest index.
1113

1114 1115 1116 1117 1118 1119 1120 1121
  /// Constructs an empty [Paint] object with all fields initialized to
  /// their defaults.
  Paint() {
    if (enableDithering) {
      _dither = true;
    }
  }

1122 1123 1124
  /// Whether to apply anti-aliasing to lines and images drawn on the
  /// canvas.
  ///
1125
  /// Defaults to true.
1126
  bool get isAntiAlias {
1127 1128
    return _data.getInt32(_kIsAntiAliasOffset, _kFakeHostEndian) == 0;
  }
1129
  set isAntiAlias(bool value) {
1130 1131 1132 1133 1134 1135
    // We encode true as zero and false as one because the default value, which
    // we always encode as zero, is true.
    final int encoded = value ? 0 : 1;
    _data.setInt32(_kIsAntiAliasOffset, encoded, _kFakeHostEndian);
  }

1136
  // Must be kept in sync with the default in paint.cc.
1137
  static const int _kColorDefault = 0xFF000000;
1138 1139 1140

  /// The color to use when stroking or filling a shape.
  ///
1141
  /// Defaults to opaque black.
1142 1143 1144 1145 1146 1147 1148 1149 1150
  ///
  /// See also:
  ///
  ///  * [style], which controls whether to stroke or fill (or both).
  ///  * [colorFilter], which overrides [color].
  ///  * [shader], which overrides [color] with more elaborate effects.
  ///
  /// This color is not used when compositing. To colorize a layer, use
  /// [colorFilter].
1151
  Color get color {
1152
    final int encoded = _data.getInt32(_kColorOffset, _kFakeHostEndian);
D
Dan Field 已提交
1153
    return Color(encoded ^ _kColorDefault);
1154
  }
1155 1156
  set color(Color value) {
    assert(value != null); // ignore: unnecessary_null_comparison
1157 1158 1159 1160
    final int encoded = value.value ^ _kColorDefault;
    _data.setInt32(_kColorOffset, encoded, _kFakeHostEndian);
  }

1161
  // Must be kept in sync with the default in paint.cc.
1162
  static final int _kBlendModeDefault = BlendMode.srcOver.index;
1163

1164
  /// A blend mode to apply when a shape is drawn or a layer is composited.
1165 1166 1167 1168 1169 1170 1171 1172 1173
  ///
  /// The source colors are from the shape being drawn (e.g. from
  /// [Canvas.drawPath]) or layer being composited (the graphics that were drawn
  /// between the [Canvas.saveLayer] and [Canvas.restore] calls), after applying
  /// the [colorFilter], if any.
  ///
  /// The destination colors are from the background onto which the shape or
  /// layer is being composited.
  ///
1174
  /// Defaults to [BlendMode.srcOver].
1175 1176 1177 1178
  ///
  /// See also:
  ///
  ///  * [Canvas.saveLayer], which uses its [Paint]'s [blendMode] to composite
1179 1180 1181
  ///    the layer when [Canvas.restore] is called.
  ///  * [BlendMode], which discusses the user of [Canvas.saveLayer] with
  ///    [blendMode].
1182
  BlendMode get blendMode {
1183 1184
    final int encoded = _data.getInt32(_kBlendModeOffset, _kFakeHostEndian);
    return BlendMode.values[encoded ^ _kBlendModeDefault];
1185
  }
1186 1187
  set blendMode(BlendMode value) {
    assert(value != null); // ignore: unnecessary_null_comparison
1188 1189
    final int encoded = value.index ^ _kBlendModeDefault;
    _data.setInt32(_kBlendModeOffset, encoded, _kFakeHostEndian);
1190 1191 1192 1193 1194
  }

  /// Whether to paint inside shapes, the edges of shapes, or both.
  ///
  /// Defaults to [PaintingStyle.fill].
1195
  PaintingStyle get style {
1196 1197
    return PaintingStyle.values[_data.getInt32(_kStyleOffset, _kFakeHostEndian)];
  }
1198 1199
  set style(PaintingStyle value) {
    assert(value != null); // ignore: unnecessary_null_comparison
1200 1201 1202 1203 1204
    final int encoded = value.index;
    _data.setInt32(_kStyleOffset, encoded, _kFakeHostEndian);
  }

  /// How wide to make edges drawn when [style] is set to
1205 1206
  /// [PaintingStyle.stroke]. The width is given in logical pixels measured in
  /// the direction orthogonal to the direction of the path.
1207 1208
  ///
  /// Defaults to 0.0, which correspond to a hairline width.
1209
  double get strokeWidth {
1210 1211
    return _data.getFloat32(_kStrokeWidthOffset, _kFakeHostEndian);
  }
1212 1213
  set strokeWidth(double value) {
    assert(value != null); // ignore: unnecessary_null_comparison
1214 1215 1216 1217 1218
    final double encoded = value;
    _data.setFloat32(_kStrokeWidthOffset, encoded, _kFakeHostEndian);
  }

  /// The kind of finish to place on the end of lines drawn when
1219
  /// [style] is set to [PaintingStyle.stroke].
1220 1221
  ///
  /// Defaults to [StrokeCap.butt], i.e. no caps.
1222
  StrokeCap get strokeCap {
1223 1224
    return StrokeCap.values[_data.getInt32(_kStrokeCapOffset, _kFakeHostEndian)];
  }
1225 1226
  set strokeCap(StrokeCap value) {
    assert(value != null); // ignore: unnecessary_null_comparison
1227 1228 1229
    final int encoded = value.index;
    _data.setInt32(_kStrokeCapOffset, encoded, _kFakeHostEndian);
  }
1230

1231 1232 1233 1234 1235
  /// The kind of finish to place on the joins between segments.
  ///
  /// This applies to paths drawn when [style] is set to [PaintingStyle.stroke],
  /// It does not apply to points drawn as lines with [Canvas.drawPoints].
  ///
1236 1237 1238 1239
  /// Defaults to [StrokeJoin.miter], i.e. sharp corners.
  ///
  /// Some examples of joins:
  ///
1240
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_4_join.mp4}
1241
  ///
1242
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/round_join.mp4}
1243
  ///
1244
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/bevel_join.mp4}
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
  ///
  /// The centers of the line segments are colored in the diagrams above to
  /// highlight the joins, but in normal usage the join is the same color as the
  /// line.
  ///
  /// See also:
  ///
  ///  * [strokeMiterLimit] to control when miters are replaced by bevels when
  ///    this is set to [StrokeJoin.miter].
  ///  * [strokeCap] to control what is drawn at the ends of the stroke.
  ///  * [StrokeJoin] for the definitive list of stroke joins.
1256
  StrokeJoin get strokeJoin {
1257 1258
    return StrokeJoin.values[_data.getInt32(_kStrokeJoinOffset, _kFakeHostEndian)];
  }
1259 1260
  set strokeJoin(StrokeJoin value) {
    assert(value != null); // ignore: unnecessary_null_comparison
1261 1262 1263 1264 1265
    final int encoded = value.index;
    _data.setInt32(_kStrokeJoinOffset, encoded, _kFakeHostEndian);
  }

  // Must be kept in sync with the default in paint.cc.
1266
  static const double _kStrokeMiterLimitDefault = 4.0;
1267 1268 1269 1270 1271

  /// The limit for miters to be drawn on segments when the join is set to
  /// [StrokeJoin.miter] and the [style] is set to [PaintingStyle.stroke]. If
  /// this limit is exceeded, then a [StrokeJoin.bevel] join will be drawn
  /// instead. This may cause some 'popping' of the corners of a path if the
1272
  /// angle between line segments is animated, as seen in the diagrams below.
1273 1274 1275 1276 1277
  ///
  /// This limit is expressed as a limit on the length of the miter.
  ///
  /// Defaults to 4.0.  Using zero as a limit will cause a [StrokeJoin.bevel]
  /// join to be used all the time.
1278
  ///
1279
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_0_join.mp4}
1280
  ///
1281
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_4_join.mp4}
1282
  ///
1283
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_6_join.mp4}
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
  ///
  /// The centers of the line segments are colored in the diagrams above to
  /// highlight the joins, but in normal usage the join is the same color as the
  /// line.
  ///
  /// See also:
  ///
  ///  * [strokeJoin] to control the kind of finish to place on the joins
  ///    between segments.
  ///  * [strokeCap] to control what is drawn at the ends of the stroke.
1294
  double get strokeMiterLimit {
1295 1296
    return _data.getFloat32(_kStrokeMiterLimitOffset, _kFakeHostEndian);
  }
1297 1298
  set strokeMiterLimit(double value) {
    assert(value != null); // ignore: unnecessary_null_comparison
1299 1300 1301 1302
    final double encoded = value - _kStrokeMiterLimitDefault;
    _data.setFloat32(_kStrokeMiterLimitOffset, encoded, _kFakeHostEndian);
  }

1303 1304 1305 1306
  /// A mask filter (for example, a blur) to apply to a shape after it has been
  /// drawn but before it has been composited into the image.
  ///
  /// See [MaskFilter] for details.
1307
  MaskFilter? get maskFilter {
1308 1309 1310 1311
    switch (_data.getInt32(_kMaskFilterOffset, _kFakeHostEndian)) {
      case MaskFilter._TypeNone:
        return null;
      case MaskFilter._TypeBlur:
D
Dan Field 已提交
1312
        return MaskFilter.blur(
1313 1314 1315 1316 1317
          BlurStyle.values[_data.getInt32(_kMaskFilterBlurStyleOffset, _kFakeHostEndian)],
          _data.getFloat32(_kMaskFilterSigmaOffset, _kFakeHostEndian),
        );
    }
    return null;
1318
  }
1319
  set maskFilter(MaskFilter? value) {
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    if (value == null) {
      _data.setInt32(_kMaskFilterOffset, MaskFilter._TypeNone, _kFakeHostEndian);
      _data.setInt32(_kMaskFilterBlurStyleOffset, 0, _kFakeHostEndian);
      _data.setFloat32(_kMaskFilterSigmaOffset, 0.0, _kFakeHostEndian);
    } else {
      // For now we only support one kind of MaskFilter, so we don't need to
      // check what the type is if it's not null.
      _data.setInt32(_kMaskFilterOffset, MaskFilter._TypeBlur, _kFakeHostEndian);
      _data.setInt32(_kMaskFilterBlurStyleOffset, value._style.index, _kFakeHostEndian);
      _data.setFloat32(_kMaskFilterSigmaOffset, value._sigma, _kFakeHostEndian);
    }
1331
  }
1332 1333 1334 1335

  /// Controls the performance vs quality trade-off to use when applying
  /// filters, such as [maskFilter], or when drawing images, as with
  /// [Canvas.drawImageRect] or [Canvas.drawImageNine].
1336 1337
  ///
  /// Defaults to [FilterQuality.none].
1338
  // TODO(ianh): verify that the image drawing methods actually respect this
1339
  FilterQuality get filterQuality {
1340 1341
    return FilterQuality.values[_data.getInt32(_kFilterQualityOffset, _kFakeHostEndian)];
  }
1342 1343
  set filterQuality(FilterQuality value) {
    assert(value != null); // ignore: unnecessary_null_comparison
1344 1345 1346
    final int encoded = value.index;
    _data.setInt32(_kFilterQualityOffset, encoded, _kFakeHostEndian);
  }
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357

  /// The shader to use when stroking or filling a shape.
  ///
  /// When this is null, the [color] is used instead.
  ///
  /// See also:
  ///
  ///  * [Gradient], a shader that paints a color gradient.
  ///  * [ImageShader], a shader that tiles an [Image].
  ///  * [colorFilter], which overrides [shader].
  ///  * [color], which is used if [shader] and [colorFilter] are null.
1358 1359
  Shader? get shader {
    return _objects?[_kShaderIndex] as Shader?;
1360
  }
1361 1362
  set shader(Shader? value) {
    _ensureObjectsInitialized()[_kShaderIndex] = value;
1363
  }
1364 1365 1366 1367 1368 1369 1370

  /// A color filter to apply when a shape is drawn or when a layer is
  /// composited.
  ///
  /// See [ColorFilter] for details.
  ///
  /// When a shape is being drawn, [colorFilter] overrides [color] and [shader].
1371 1372
  ColorFilter? get colorFilter {
    return _objects?[_kColorFilterIndex]?.creator as ColorFilter?;
1373
  }
1374

1375 1376
  set colorFilter(ColorFilter? value) {
    final _ColorFilter? nativeFilter = value?._toNativeColorFilter();
D
Dan Field 已提交
1377
    if (nativeFilter == null) {
1378
      if (_objects != null) {
1379
        _objects![_kColorFilterIndex] = null;
1380
      }
1381
    } else {
1382
      _ensureObjectsInitialized()[_kColorFilterIndex] = nativeFilter;
1383 1384 1385
    }
  }

1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
  /// The [ImageFilter] to use when drawing raster images.
  ///
  /// For example, to blur an image using [Canvas.drawImage], apply an
  /// [ImageFilter.blur]:
  ///
  /// ```dart
  /// import 'dart:ui' as ui;
  ///
  /// ui.Image image;
  ///
  /// void paint(Canvas canvas, Size size) {
  ///   canvas.drawImage(
  ///     image,
  ///     Offset.zero,
  ///     Paint()..imageFilter = ui.ImageFilter.blur(sigmaX: .5, sigmaY: .5),
  ///   );
  /// }
  /// ```
  ///
  /// See also:
  ///
  ///  * [MaskFilter], which is used for drawing geometry.
1408 1409
  ImageFilter? get imageFilter {
    return _objects?[_kImageFilterIndex]?.creator as ImageFilter?;
1410
  }
J
Jim Graham 已提交
1411

1412
  set imageFilter(ImageFilter? value) {
J
Jim Graham 已提交
1413 1414
    if (value == null) {
      if (_objects != null) {
1415
        _objects![_kImageFilterIndex] = null;
J
Jim Graham 已提交
1416 1417
      }
    } else {
1418 1419 1420
      final List<dynamic> objects = _ensureObjectsInitialized();
      if (objects[_kImageFilterIndex]?.creator != value) {
        objects[_kImageFilterIndex] = value._toNativeImageFilter();
J
Jim Graham 已提交
1421 1422
      }
    }
1423 1424
  }

1425 1426
  /// Whether the colors of the image are inverted when drawn.
  ///
D
Dan Field 已提交
1427
  /// Inverting the colors of an image applies a new color filter that will
1428 1429
  /// be composed with any user provided color filters. This is primarily
  /// used for implementing smart invert on iOS.
1430
  bool get invertColors {
1431 1432
    return _data.getInt32(_kInvertColorOffset, _kFakeHostEndian) == 1;
  }
1433
  set invertColors(bool value) {
1434 1435 1436
    _data.setInt32(_kInvertColorOffset, value ? 1 : 0, _kFakeHostEndian);
  }

1437
  bool get _dither {
1438 1439
    return _data.getInt32(_kDitherOffset, _kFakeHostEndian) == 1;
  }
1440
  set _dither(bool value) {
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
    _data.setInt32(_kDitherOffset, value ? 1 : 0, _kFakeHostEndian);
  }

  /// Whether to dither the output when drawing images.
  ///
  /// If false, the default value, dithering will be enabled when the input
  /// color depth is higher than the output color depth. For example,
  /// drawing an RGB8 image onto an RGB565 canvas.
  ///
  /// This value also controls dithering of [shader]s, which can make
  /// gradients appear smoother.
  ///
  /// Whether or not dithering affects the output is implementation defined.
  /// Some implementations may choose to ignore this completely, if they're
  /// unable to control dithering.
  ///
  /// To ensure that dithering is consistently enabled for your entire
  /// application, set this to true before invoking any drawing related code.
1459
  static bool enableDithering = false;
1460

1461
  @override
1462
  String toString() {
D
Dan Field 已提交
1463 1464 1465
    if (const bool.fromEnvironment('dart.vm.product', defaultValue: false)) {
      return super.toString();
    }
D
Dan Field 已提交
1466
    final StringBuffer result = StringBuffer();
1467 1468
    String semicolon = '';
    result.write('Paint(');
1469
    if (style == PaintingStyle.stroke) {
1470
      result.write('$style');
1471
      if (strokeWidth != 0.0)
1472
        result.write(' ${strokeWidth.toStringAsFixed(1)}');
1473 1474
      else
        result.write(' hairline');
1475
      if (strokeCap != StrokeCap.butt)
1476
        result.write(' $strokeCap');
1477 1478 1479 1480 1481 1482
      if (strokeJoin == StrokeJoin.miter) {
        if (strokeMiterLimit != _kStrokeMiterLimitDefault)
          result.write(' $strokeJoin up to ${strokeMiterLimit.toStringAsFixed(1)}');
      } else {
        result.write(' $strokeJoin');
      }
1483 1484 1485 1486 1487 1488
      semicolon = '; ';
    }
    if (isAntiAlias != true) {
      result.write('${semicolon}antialias off');
      semicolon = '; ';
    }
1489
    if (color != const Color(_kColorDefault)) {
1490
      result.write('$semicolon$color');
1491 1492
      semicolon = '; ';
    }
1493
    if (blendMode.index != _kBlendModeDefault) {
1494
      result.write('$semicolon$blendMode');
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
      semicolon = '; ';
    }
    if (colorFilter != null) {
      result.write('${semicolon}colorFilter: $colorFilter');
      semicolon = '; ';
    }
    if (maskFilter != null) {
      result.write('${semicolon}maskFilter: $maskFilter');
      semicolon = '; ';
    }
1505
    if (filterQuality != FilterQuality.none) {
1506 1507 1508
      result.write('${semicolon}filterQuality: $filterQuality');
      semicolon = '; ';
    }
1509
    if (shader != null) {
1510
      result.write('${semicolon}shader: $shader');
1511 1512
      semicolon = '; ';
    }
1513 1514 1515 1516
    if (imageFilter != null) {
      result.write('${semicolon}imageFilter: $imageFilter');
      semicolon = '; ';
    }
1517 1518
    if (invertColors)
      result.write('${semicolon}invert: $invertColors');
1519 1520
    if (_dither)
      result.write('${semicolon}dither: $_dither');
1521 1522 1523 1524 1525
    result.write(')');
    return result.toString();
  }
}

1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
/// The format in which image bytes should be returned when using
/// [Image.toByteData].
enum ImageByteFormat {
  /// Raw RGBA format.
  ///
  /// Unencoded bytes, in RGBA row-primary form, 8 bits per channel.
  rawRgba,

  /// Raw unmodified format.
  ///
  /// Unencoded bytes, in the image's existing format. For example, a grayscale
  /// image may use a single 8-bit channel for each pixel.
  rawUnmodified,

  /// PNG format.
  ///
  /// A loss-less compression format for images. This format is well suited for
  /// images with hard edges, such as screenshots or sprites, and images with
  /// text. Transparency is supported. The PNG format supports images up to
  /// 2,147,483,647 pixels in either dimension, though in practice available
  /// memory provides a more immediate limitation on maximum image size.
  ///
  /// PNG images normally use the `.png` file extension and the `image/png` MIME
  /// type.
  ///
  /// See also:
  ///
  ///  * <https://en.wikipedia.org/wiki/Portable_Network_Graphics>, the Wikipedia page on PNG.
  ///  * <https://tools.ietf.org/rfc/rfc2083.txt>, the PNG standard.
  png,
}

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
/// The format of pixel data given to [decodeImageFromPixels].
enum PixelFormat {
  /// Each pixel is 32 bits, with the highest 8 bits encoding red, the next 8
  /// bits encoding green, the next 8 bits encoding blue, and the lowest 8 bits
  /// encoding alpha.
  rgba8888,

  /// Each pixel is 32 bits, with the highest 8 bits encoding blue, the next 8
  /// bits encoding green, the next 8 bits encoding red, and the lowest 8 bits
  /// encoding alpha.
  bgra8888,
}

I
Ian Hickson 已提交
1571 1572
/// Opaque handle to raw decoded image data (pixels).
///
1573
/// To obtain an [Image] object, use the [ImageDescriptor] API.
I
Ian Hickson 已提交
1574
///
1575
/// To draw an [Image], use one of the methods on the [Canvas] class, such as
I
Ian Hickson 已提交
1576
/// [Canvas.drawImage].
1577
///
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
/// A class or method that receives an image object must call [dispose] on the
/// handle when it is no longer needed. To create a shareable reference to the
/// underlying image, call [clone]. The method or object that recieves
/// the new instance will then be responsible for disposing it, and the
/// underlying image itself will be disposed when all outstanding handles are
/// disposed.
///
/// If `dart:ui` passes an `Image` object and the recipient wishes to share
/// that handle with other callers, [clone] must be called _before_ [dispose].
/// A handle that has been disposed cannot create new handles anymore.
///
1589 1590
/// See also:
///
1591
///  * [Image](https://api.flutter.dev/flutter/widgets/Image-class.html), the class in the [widgets] library.
1592 1593 1594
///  * [ImageDescriptor], which allows reading information about the image and
///    creating a codec to decode it.
///  * [instantiateImageCodec], a utility method that wraps [ImageDescriptor].
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
class Image {
  Image._(this._image) {
    assert(() {
      _debugStack = StackTrace.current;
      return true;
    }());
    _image._handles.add(this);
  }

  // C++ unit tests access this.
1605
  @pragma('vm:entry-point')
1606 1607 1608
  final _Image _image;

  StackTrace? _debugStack;
1609

I
Ian Hickson 已提交
1610
  /// The number of image pixels along the image's horizontal axis.
1611 1612 1613 1614
  int get width {
    assert(!_disposed && !_image._disposed);
    return _image.width;
  }
I
Ian Hickson 已提交
1615 1616

  /// The number of image pixels along the image's vertical axis.
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
  int get height {
    assert(!_disposed && !_image._disposed);
    return _image.height;
  }

  bool _disposed = false;
  /// Release this handle's claim on the underlying Image. This handle is no
  /// longer usable after this method is called.
  ///
  /// Once all outstanding handles have been disposed, the underlying image will
  /// be disposed as well.
  ///
  /// In debug mode, [debugGetOpenHandleStackTraces] will return a list of
  /// [StackTrace] objects from all open handles' creation points. This is
  /// useful when trying to determine what parts of the program are keeping an
  /// image resident in memory.
  void dispose() {
    assert(!_disposed && !_image._disposed);
    assert(_image._handles.contains(this));
    _disposed = true;
    final bool removed = _image._handles.remove(this);
    assert(removed);
    if (_image._handles.isEmpty) {
      _image.dispose();
    }
  }
1643

D
Dan Field 已提交
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
  /// Whether this reference to the underlying image is [dispose]d.
  ///
  /// This only returns a valid value if asserts are enabled, and must not be
  /// used otherwise.
  bool get debugDisposed {
    bool? disposed;
    assert(() {
      disposed = _disposed;
      return true;
    }());
    return disposed ?? (throw StateError('Image.debugDisposed is only available when asserts are enabled.'));
  }

1657
  /// Converts the [Image] object into a byte array.
1658
  ///
1659 1660
  /// The [format] argument specifies the format in which the bytes will be
  /// returned.
1661
  ///
1662
  /// Returns a future that completes with the binary image data or an error
1663
  /// if encoding fails.
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
  Future<ByteData?> toByteData({ImageByteFormat format = ImageByteFormat.rawRgba}) {
    assert(!_disposed && !_image._disposed);
    return _image.toByteData(format: format);
  }

  /// If asserts are enabled, returns the [StackTrace]s of each open handle from
  /// [clone], in creation order.
  ///
  /// If asserts are disabled, this method always returns null.
  List<StackTrace>? debugGetOpenHandleStackTraces() {
    List<StackTrace>? stacks;
    assert(() {
      stacks = _image._handles.map((Image handle) => handle._debugStack!).toList();
      return true;
    }());
    return stacks;
  }

  /// Creates a disposable handle to this image.
  ///
  /// Holders of an [Image] must dispose of the image when they no longer need
  /// to access it or draw it. However, once the underlying image is disposed,
  /// it is no longer possible to use it. If a holder of an image needs to share
  /// access to that image with another object or method, [clone] creates a
  /// duplicate handle. The underlying image will only be disposed once all
  /// outstanding handles are disposed. This allows for safe sharing of image
  /// references while still disposing of the underlying resources when all
  /// consumers are finished.
  ///
  /// It is safe to pass an [Image] handle to another object or method if the
  /// current holder no longer needs it.
  ///
D
Dan Field 已提交
1696 1697 1698 1699
  /// To check whether two [Image] references are refering to the same
  /// underlying image memory, use [isCloneOf] rather than the equality operator
  /// or [identical].
  ///
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
  /// The following example demonstrates valid usage.
  ///
  /// ```dart
  /// import 'dart:async';
  ///
  /// Future<Image> _loadImage(int width, int height) {
  ///   final Completer<Image> completer = Completer<Image>();
  ///   decodeImageFromPixels(
  ///     Uint8List.fromList(List<int>.filled(width * height * 4, 0xFF)),
  ///     width,
  ///     height,
  ///     PixelFormat.rgba8888,
  ///     // Don't worry about disposing or cloning this image - responsibility
  ///     // is transferred to the caller, and that is safe since this method
  ///     // will not touch it again.
  ///     (Image image) => completer.complete(image),
  ///   );
  ///   return completer.future;
  /// }
  ///
  /// Future<void> main() async {
  ///   final Image image = await _loadImage(5, 5);
  ///   // Make sure to clone the image, because MyHolder might dispose it
  ///   // and we need to access it again.
  ///   final MyImageHolder holder = MyImageHolder(image.clone());
  ///   final MyImageHolder holder2 = MyImageHolder(image.clone());
  ///   // Now we dispose it because we won't need it again.
  ///   image.dispose();
  ///
  ///   final PictureRecorder recorder = PictureRecorder();
  ///   final Canvas canvas = Canvas(recorder);
  ///
  ///   holder.draw(canvas);
  ///   holder.dispose();
  ///
  ///   canvas.translate(50, 50);
  ///   holder2.draw(canvas);
  ///   holder2.dispose();
  /// }
  ///
  /// class MyImageHolder {
  ///   MyImageLoader(this.image);
  ///
  ///   final Image image;
  ///
  ///   void draw(Canvas canvas) {
  ///     canvas.drawImage(image, Offset.zero, Paint());
  ///   }
  ///
  ///   void dispose() => image.dispose();
  /// }
  /// ```
  ///
  /// The returned object behaves identically to this image. Calling
  /// [dispose] on it will only dispose the underlying native resources if it
  /// is the last remaining handle.
  Image clone() {
    if (_disposed) {
      throw StateError(
        'Cannot clone a disposed image.\n'
        'The clone() method of a previously-disposed Image was called. Once an '
        'Image object has been disposed, it can no longer be used to create '
        'handles, as the underlying data may have been released.'
      );
    }
    assert(!_image._disposed);
    return Image._(_image);
  }

D
Dan Field 已提交
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
  /// Returns true if `other` is a [clone] of this and thus shares the same
  /// underlying image memory, even if this or `other` is [dispose]d.
  ///
  /// This method may return false for two images that were decoded from the
  /// same underlying asset, if they are not sharing the same memory. For
  /// example, if the same file is decoded using [instantiateImageCodec] twice,
  /// or the same bytes are decoded using [decodeImageFromPixels] twice, there
  /// will be two distinct [Image]s that render the same but do not share
  /// underlying memory, and so will not be treated as clones of each other.
  bool isCloneOf(Image other) => other._image == _image;

1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
  @override
  String toString() => _image.toString();
}

@pragma('vm:entry-point')
class _Image extends NativeFieldWrapperClass2 {
  // This class is created by the engine, and should not be instantiated
  // or extended directly.
  //
  // _Images are always handed out wrapped in [Image]s. To create an [Image],
  // use the ImageDescriptor API.
  @pragma('vm:entry-point')
  _Image._();

  int get width native 'Image_width';

  int get height native 'Image_height';

1798
  Future<ByteData?> toByteData({ImageByteFormat format = ImageByteFormat.rawRgba}) {
1799
    return _futurize((_Callback<ByteData> callback) {
1800
      return _toByteData(format.index, (Uint8List? encoded) {
1801
        callback(encoded!.buffer.asByteData());
1802 1803 1804 1805 1806
      });
    });
  }

  /// Returns an error message on failure, null on success.
1807
  String? _toByteData(int format, _Callback<Uint8List?> callback) native 'Image_toByteData';
1808

1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
  bool _disposed = false;
  void dispose() {
    assert(!_disposed);
    assert(
      _handles.isEmpty,
      'Attempted to dispose of an Image object that has ${_handles.length} '
      'open handles.\n'
      'If you see this, it is a bug in dart:ui. Please file an issue at '
      'https://github.com/flutter/flutter/issues/new.',
    );
    _disposed = true;
    _dispose();
  }

  void _dispose() native 'Image_dispose';

  Set<Image> _handles = <Image>{};
A
Adam Barth 已提交
1826

1827
  @override
1828
  String toString() => '[$width\u00D7$height]';
1829 1830
}

1831
/// Callback signature for [decodeImageFromList].
1832
typedef ImageDecoderCallback = void Function(Image result);
1833

1834
/// Information for a single frame of an animation.
1835
///
1836 1837
/// To obtain an instance of the [FrameInfo] interface, see
/// [Codec.getNextFrame].
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
///
/// The recipient of an instance of this class is responsible for calling
/// [Image.dispose] on [image]. To share the image with other interested
/// parties, use [Image.clone]. If the [FrameInfo] object itself is passed to
/// another method or object, that method or object must assume it is
/// responsible for disposing the image when done, and the passer must not
/// access the [image] after that point.
///
/// For example, the following code sample is incorrect:
///
/// ```dart
/// /// BAD
/// Future<void> nextFrameRoutine(Codec codec) async {
///   final FrameInfo frameInfo = await codec.getNextFrame();
///   _cacheImage(frameInfo);
///   // ERROR - _cacheImage is now responsible for disposing the image, and
///   // the image may not be available any more for this drawing routine.
///   _drawImage(frameInfo);
///   // ERROR again - the previous methods might or might not have created
///   // handles to the image.
///   frameInfo.image.dispose();
/// }
/// ```
///
/// Correct usage is:
///
/// ```dart
/// /// GOOD
/// Future<void> nextFrameRoutine(Codec codec) async {
///   final FrameInfo frameInfo = await codec.getNextFrame();
///   _cacheImage(frameInfo.image.clone(), frameInfo.duration);
///   _drawImage(frameInfo.image.clone(), frameInfo.duration);
///   // This method is done with its handle, and has passed handles to its
///   // clients already.
///   // The image will live until those clients dispose of their handles, and
///   // this one must not be disposed since it will not be used again.
///   frameInfo.image.dispose();
/// }
/// ```
class FrameInfo {
1878 1879 1880 1881 1882
  /// This class is created by the engine, and should not be instantiated
  /// or extended directly.
  ///
  /// To obtain an instance of the [FrameInfo] interface, see
  /// [Codec.getNextFrame].
1883
  FrameInfo._({required this.duration, required this.image});
1884

1885
  /// The duration this frame should be shown.
1886 1887 1888 1889
  ///
  /// A zero duration indicates that the frame should be shown indefinitely.
  final Duration duration;

1890

1891
  /// The [Image] object for this frame.
1892 1893 1894 1895 1896
  ///
  /// This object must be disposed by the recipient of this frame info.
  ///
  /// To share this image with other interested parties, use [Image.clone].
  final Image image;
1897 1898 1899
}

/// A handle to an image codec.
I
Ian Hickson 已提交
1900 1901 1902 1903 1904 1905
///
/// This class is created by the engine, and should not be instantiated
/// or extended directly.
///
/// To obtain an instance of the [Codec] interface, see
/// [instantiateImageCodec].
S
sjindel-google 已提交
1906
@pragma('vm:entry-point')
1907
class Codec extends NativeFieldWrapperClass2 {
I
Ian Hickson 已提交
1908 1909 1910 1911 1912 1913
  //
  // This class is created by the engine, and should not be instantiated
  // or extended directly.
  //
  // To obtain an instance of the [Codec] interface, see
  // [instantiateImageCodec].
1914
  @pragma('vm:entry-point')
1915 1916
  Codec._();

1917
  int? _cachedFrameCount;
1918
  /// Number of frames in this image.
1919 1920
  int get frameCount => _cachedFrameCount ??= _frameCount;
  int get _frameCount native 'Codec_frameCount';
1921

1922
  int? _cachedRepetitionCount;
1923 1924 1925 1926
  /// Number of times to repeat the animation.
  ///
  /// * 0 when the animation should be played once.
  /// * -1 for infinity repetitions.
1927 1928 1929
  int get repetitionCount => _cachedRepetitionCount ??= _repetitionCount;
  int get _repetitionCount native 'Codec_repetitionCount';

1930
  /// Fetches the next animation frame.
1931 1932
  ///
  /// Wraps back to the first frame after returning the last frame.
1933
  ///
1934
  /// The returned future can complete with an error if the decoding has failed.
1935 1936 1937 1938
  ///
  /// The caller of this method is responsible for disposing the
  /// [FrameInfo.image] on the returned object.
  Future<FrameInfo> getNextFrame() async {
D
Dan Field 已提交
1939 1940 1941 1942
    final Completer<FrameInfo> completer = Completer<FrameInfo>.sync();
    final String? error = _getNextFrame((_Image? image, int durationMilliseconds) {
      if (image == null) {
        throw Exception('Codec failed to produce an image, possibly due to invalid image data.');
1943
      }
D
Dan Field 已提交
1944 1945 1946 1947 1948 1949 1950
      completer.complete(FrameInfo._(
        image: Image._(image),
        duration: Duration(milliseconds: durationMilliseconds),
      ));
    });
    if (error != null) {
      throw Exception(error);
1951
    }
D
Dan Field 已提交
1952
    return await completer.future;
1953 1954
  }

1955
  /// Returns an error message on failure, null on success.
1956
  String? _getNextFrame(void Function(_Image?, int) callback) native 'Codec_getNextFrame';
1957 1958 1959

  /// Release the resources used by this object. The object is no longer usable
  /// after this method is called.
1960
  void dispose() native 'Codec_dispose';
1961 1962
}

1963
/// Instantiates an image [Codec].
1964
///
1965 1966 1967 1968 1969
/// This method is a convenience wrapper around the [ImageDescriptor] API, and
/// using [ImageDescriptor] directly is preferred since it allows the caller to
/// make better determinations about how and whether to use the `targetWidth`
/// and `targetHeight` parameters.
///
1970
/// The `list` parameter is the binary image data (e.g a PNG or GIF binary data).
1971
/// The data can be for either static or animated images. The following image
1972
/// formats are supported: {@macro dart.ui.imageFormats}
1973
///
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
/// The `targetWidth` and `targetHeight` arguments specify the size of the
/// output image, in image pixels. If they are not equal to the intrinsic
/// dimensions of the image, then the image will be scaled after being decoded.
/// If the `allowUpscaling` parameter is not set to true, both dimensions will
/// be capped at the intrinsic dimensions of the image, even if only one of
/// them would have exceeded those intrinsic dimensions. If exactly one of these
/// two arguments is specified, then the aspect ratio will be maintained while
/// forcing the image to match the other given dimension. If neither is
/// specified, then the image maintains its intrinsic size.
///
/// Scaling the image to larger than its intrinsic size should usually be
/// avoided, since it causes the image to use more memory than necessary.
/// Instead, prefer scaling the [Canvas] transform. If the image must be scaled
/// up, the `allowUpscaling` parameter must be set to true.
1988
///
1989 1990
/// The returned future can complete with an error if the image decoding has
/// failed.
1991 1992
Future<Codec> instantiateImageCodec(
  Uint8List list, {
1993 1994
  int? targetWidth,
  int? targetHeight,
1995
  bool allowUpscaling = true,
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
}) async {
  final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(list);
  final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer);
  if (!allowUpscaling) {
    if (targetWidth != null && targetWidth > descriptor.width) {
      targetWidth = descriptor.width;
    }
    if (targetHeight != null && targetHeight > descriptor.height) {
      targetHeight = descriptor.height;
    }
  }
  return descriptor.instantiateCodec(
    targetWidth: targetWidth,
    targetHeight: targetHeight,
  );
2011
}
2012

2013 2014
/// Loads a single image frame from a byte array into an [Image] object.
///
I
Ian Hickson 已提交
2015
/// This is a convenience wrapper around [instantiateImageCodec]. Prefer using
2016 2017
/// [instantiateImageCodec] which also supports multi frame images and offers
/// better error handling. This function swallows asynchronous errors.
2018
void decodeImageFromList(Uint8List list, ImageDecoderCallback callback) {
2019 2020 2021
  _decodeImageFromListAsync(list, callback);
}

2022 2023
Future<void> _decodeImageFromListAsync(Uint8List list,
                                       ImageDecoderCallback callback) async {
2024 2025 2026 2027
  final Codec codec = await instantiateImageCodec(list);
  final FrameInfo frameInfo = await codec.getNextFrame();
  callback(frameInfo.image);
}
2028

2029 2030
/// Convert an array of pixel values into an [Image] object.
///
2031 2032
/// The `pixels` parameter is the pixel data in the encoding described by
/// `format`.
2033
///
2034 2035 2036
/// The `rowBytes` parameter is the number of bytes consumed by each row of
/// pixels in the data buffer. If unspecified, it defaults to `width` multiplied
/// by the number of bytes per pixel in the provided `format`.
2037
///
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
/// The `targetWidth` and `targetHeight` arguments specify the size of the
/// output image, in image pixels. If they are not equal to the intrinsic
/// dimensions of the image, then the image will be scaled after being decoded.
/// If the `allowUpscaling` parameter is not set to true, both dimensions will
/// be capped at the intrinsic dimensions of the image, even if only one of
/// them would have exceeded those intrinsic dimensions. If exactly one of these
/// two arguments is specified, then the aspect ratio will be maintained while
/// forcing the image to match the other given dimension. If neither is
/// specified, then the image maintains its intrinsic size.
///
/// Scaling the image to larger than its intrinsic size should usually be
/// avoided, since it causes the image to use more memory than necessary.
/// Instead, prefer scaling the [Canvas] transform. If the image must be scaled
/// up, the `allowUpscaling` parameter must be set to true.
2052
void decodeImageFromPixels(
2053 2054 2055 2056
  Uint8List pixels,
  int width,
  int height,
  PixelFormat format,
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
  ImageDecoderCallback callback, {
  int? rowBytes,
  int? targetWidth,
  int? targetHeight,
  bool allowUpscaling = true,
}) {
  if (targetWidth != null) {
    assert(allowUpscaling || targetWidth <= width);
  }
  if (targetHeight != null) {
    assert(allowUpscaling || targetHeight <= height);
  }

2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
  ImmutableBuffer.fromUint8List(pixels)
    .then((ImmutableBuffer buffer) {
      final ImageDescriptor descriptor = ImageDescriptor.raw(
        buffer,
        width: width,
        height: height,
        rowBytes: rowBytes,
        pixelFormat: format,
      );

      if (!allowUpscaling) {
        if (targetWidth != null && targetWidth! > descriptor.width) {
          targetWidth = descriptor.width;
        }
        if (targetHeight != null && targetHeight! > descriptor.height) {
          targetHeight = descriptor.height;
        }
      }

      descriptor
        .instantiateCodec(
          targetWidth: targetWidth,
          targetHeight: targetHeight,
        )
        .then((Codec codec) => codec.getNextFrame())
        .then((FrameInfo frameInfo) => callback(frameInfo.image));
2096
  });
2097 2098
}

2099 2100 2101 2102
/// Determines the winding rule that decides how the interior of a [Path] is
/// calculated.
///
/// This enum is used by the [Path.fillType] property.
A
Adam Barth 已提交
2103 2104
enum PathFillType {
  /// The interior is defined by a non-zero sum of signed edge crossings.
2105 2106 2107 2108 2109 2110 2111 2112
  ///
  /// For a given point, the point is considered to be on the inside of the path
  /// if a line drawn from the point to infinity crosses lines going clockwise
  /// around the point a different number of times than it crosses lines going
  /// counter-clockwise around that point.
  ///
  /// See: <https://en.wikipedia.org/wiki/Nonzero-rule>
  nonZero,
A
Adam Barth 已提交
2113 2114

  /// The interior is defined by an odd number of edge crossings.
2115 2116 2117 2118 2119
  ///
  /// For a given point, the point is considered to be on the inside of the path
  /// if a line drawn from the point to infinity crosses an odd number of lines.
  ///
  /// See: <https://en.wikipedia.org/wiki/Even-odd_rule>
A
Adam Barth 已提交
2120 2121 2122
  evenOdd,
}

2123
/// Strategies for combining paths.
2124
///
2125
/// See also:
2126
///
2127 2128 2129 2130 2131 2132
/// * [Path.combine], which uses this enum to decide how to combine two paths.
// Must be kept in sync with SkPathOp
enum PathOperation {
  /// Subtract the second path from the first path.
  ///
  /// For example, if the two paths are overlapping circles of equal diameter
2133
  /// but differing centers, the result would be a crescent portion of the
2134 2135 2136 2137 2138 2139 2140 2141 2142
  /// first circle that was not overlapped by the second circle.
  ///
  /// See also:
  ///
  ///  * [reverseDifference], which is the same but subtracting the first path
  ///    from the second.
  difference,
  /// Create a new path that is the intersection of the two paths, leaving the
  /// overlapping pieces of the path.
2143
  ///
2144 2145 2146
  /// For example, if the two paths are overlapping circles of equal diameter
  /// but differing centers, the result would be only the overlapping portion
  /// of the two circles.
2147
  ///
2148 2149 2150 2151
  /// See also:
  ///  * [xor], which is the inverse of this operation
  intersect,
  /// Create a new path that is the union (inclusive-or) of the two paths.
2152
  ///
2153
  /// For example, if the two paths are overlapping circles of equal diameter
2154
  /// but differing centers, the result would be a figure-eight like shape
G
Greg Spencer 已提交
2155
  /// matching the outer boundaries of both circles.
2156
  union,
2157
  /// Create a new path that is the exclusive-or of the two paths, leaving
2158
  /// everything but the overlapping pieces of the path.
2159
  ///
2160 2161
  /// For example, if the two paths are overlapping circles of equal diameter
  /// but differing centers, the figure-eight like shape less the overlapping parts
2162
  ///
2163 2164 2165 2166 2167 2168
  /// See also:
  ///  * [intersect], which is the inverse of this operation
  xor,
  /// Subtract the first path from the second path.
  ///
  /// For example, if the two paths are overlapping circles of equal diameter
2169
  /// but differing centers, the result would be a crescent portion of the
2170 2171 2172 2173 2174
  /// second circle that was not overlapped by the first circle.
  ///
  /// See also:
  ///
  ///  * [difference], which is the same but subtracting the second path
G
Greg Spencer 已提交
2175
  ///    from the first.
2176 2177 2178
  reverseDifference,
}

2179
/// A handle for the framework to hold and retain an engine layer across frames.
S
sjindel-google 已提交
2180
@pragma('vm:entry-point')
2181 2182 2183 2184 2185 2186 2187
class EngineLayer extends NativeFieldWrapperClass2 {
  /// This class is created by the engine, and should not be instantiated
  /// or extended directly.
  @pragma('vm:entry-point')
  EngineLayer._();
}

A
Adam Barth 已提交
2188 2189
/// A complex, one-dimensional subset of a plane.
///
2190
/// A path consists of a number of sub-paths, and a _current point_.
H
Hixie 已提交
2191
///
2192 2193
/// Sub-paths consist of segments of various types, such as lines,
/// arcs, or beziers. Sub-paths can be open or closed, and can
H
Hixie 已提交
2194 2195
/// self-intersect.
///
2196
/// Closed sub-paths enclose a (possibly discontiguous) region of the
2197
/// plane based on the current [fillType].
H
Hixie 已提交
2198 2199
///
/// The _current point_ is initially at the origin. After each
2200
/// operation adding a segment to a sub-path, the current point is
H
Hixie 已提交
2201 2202 2203
/// updated to the end of that segment.
///
/// Paths can be drawn on canvases using [Canvas.drawPath], and can
H
Hixie 已提交
2204
/// used to create clip regions using [Canvas.clipPath].
S
sjindel-google 已提交
2205
@pragma('vm:entry-point')
A
Adam Barth 已提交
2206
class Path extends NativeFieldWrapperClass2 {
H
Hixie 已提交
2207
  /// Create a new empty [Path] object.
2208
  @pragma('vm:entry-point')
A
Adam Barth 已提交
2209
  Path() { _constructor(); }
2210
  void _constructor() native 'Path_constructor';
A
Adam Barth 已提交
2211

2212 2213 2214
  /// Avoids creating a new native backing for the path for methods that will
  /// create it later, such as [Path.from], [shift] and [transform].
  Path._();
2215

2216
  /// Creates a copy of another [Path].
2217 2218
  ///
  /// This copy is fast and does not require additional memory unless either
2219
  /// the `source` path or the path returned by this constructor are modified.
2220
  factory Path.from(Path source) {
2221 2222 2223
    final Path clonedPath = Path._();
    source._clone(clonedPath);
    return clonedPath;
2224
  }
2225
  void _clone(Path outPath) native 'Path_clone';
2226

A
Adam Barth 已提交
2227
  /// Determines how the interior of this path is calculated.
2228 2229
  ///
  /// Defaults to the non-zero winding rule, [PathFillType.nonZero].
2230 2231
  PathFillType get fillType => PathFillType.values[_getFillType()];
  set fillType(PathFillType value) => _setFillType(value.index);
A
Adam Barth 已提交
2232

2233
  int _getFillType() native 'Path_getFillType';
2234
  void _setFillType(int fillType) native 'Path_setFillType';
A
Adam Barth 已提交
2235

2236
  /// Starts a new sub-path at the given coordinate.
2237
  void moveTo(double x, double y) native 'Path_moveTo';
H
Hixie 已提交
2238

2239
  /// Starts a new sub-path at the given offset from the current point.
2240
  void relativeMoveTo(double dx, double dy) native 'Path_relativeMoveTo';
H
Hixie 已提交
2241 2242 2243

  /// Adds a straight line segment from the current point to the given
  /// point.
2244
  void lineTo(double x, double y) native 'Path_lineTo';
H
Hixie 已提交
2245 2246 2247

  /// Adds a straight line segment from the current point to the point
  /// at the given offset from the current point.
2248
  void relativeLineTo(double dx, double dy) native 'Path_relativeLineTo';
H
Hixie 已提交
2249 2250 2251 2252

  /// Adds a quadratic bezier segment that curves from the current
  /// point to the given point (x2,y2), using the control point
  /// (x1,y1).
2253
  void quadraticBezierTo(double x1, double y1, double x2, double y2) native 'Path_quadraticBezierTo';
H
Hixie 已提交
2254 2255 2256 2257 2258

  /// Adds a quadratic bezier segment that curves from the current
  /// point to the point at the offset (x2,y2) from the current point,
  /// using the control point at the offset (x1,y1) from the current
  /// point.
2259
  void relativeQuadraticBezierTo(double x1, double y1, double x2, double y2) native 'Path_relativeQuadraticBezierTo';
H
Hixie 已提交
2260 2261 2262 2263

  /// Adds a cubic bezier segment that curves from the current point
  /// to the given point (x3,y3), using the control points (x1,y1) and
  /// (x2,y2).
2264
  void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3) native 'Path_cubicTo';
H
Hixie 已提交
2265

G
Greg Spencer 已提交
2266
  /// Adds a cubic bezier segment that curves from the current point
H
Hixie 已提交
2267 2268 2269
  /// to the point at the offset (x3,y3) from the current point, using
  /// the control points at the offsets (x1,y1) and (x2,y2) from the
  /// current point.
2270
  void relativeCubicTo(double x1, double y1, double x2, double y2, double x3, double y3) native 'Path_relativeCubicTo';
H
Hixie 已提交
2271 2272 2273 2274 2275 2276

  /// Adds a bezier segment that curves from the current point to the
  /// given point (x2,y2), using the control points (x1,y1) and the
  /// weight w. If the weight is greater than 1, then the curve is a
  /// hyperbola; if the weight equals 1, it's a parabola; and if it is
  /// less than 1, it is an ellipse.
2277
  void conicTo(double x1, double y1, double x2, double y2, double w) native 'Path_conicTo';
H
Hixie 已提交
2278 2279 2280 2281 2282 2283 2284

  /// Adds a bezier segment that curves from the current point to the
  /// point at the offset (x2,y2) from the current point, using the
  /// control point at the offset (x1,y1) from the current point and
  /// the weight w. If the weight is greater than 1, then the curve is
  /// a hyperbola; if the weight equals 1, it's a parabola; and if it
  /// is less than 1, it is an ellipse.
2285
  void relativeConicTo(double x1, double y1, double x2, double y2, double w) native 'Path_relativeConicTo';
H
Hixie 已提交
2286

2287
  /// If the `forceMoveTo` argument is false, adds a straight line
H
Hixie 已提交
2288 2289
  /// segment and an arc segment.
  ///
2290
  /// If the `forceMoveTo` argument is true, starts a new sub-path
H
Hixie 已提交
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
  /// consisting of an arc segment.
  ///
  /// In either case, the arc segment consists of the arc that follows
  /// the edge of the oval bounded by the given rectangle, from
  /// startAngle radians around the oval up to startAngle + sweepAngle
  /// radians around the oval, with zero radians being the point on
  /// the right hand side of the oval that crosses the horizontal line
  /// that intersects the center of the rectangle and with positive
  /// angles going clockwise around the oval.
  ///
2301
  /// The line segment added if `forceMoveTo` is false starts at the
H
Hixie 已提交
2302
  /// current point and ends at the start of the arc.
2303
  void arcTo(Rect rect, double startAngle, double sweepAngle, bool forceMoveTo) {
2304
    assert(_rectIsValid(rect));
2305 2306
    _arcTo(rect.left, rect.top, rect.right, rect.bottom, startAngle, sweepAngle, forceMoveTo);
  }
2307 2308
  void _arcTo(double left, double top, double right, double bottom,
              double startAngle, double sweepAngle, bool forceMoveTo) native 'Path_arcTo';
H
Hixie 已提交
2309

2310 2311
  /// Appends up to four conic curves weighted to describe an oval of `radius`
  /// and rotated by `rotation`.
2312 2313
  ///
  /// The first curve begins from the last point in the path and the last ends
2314 2315
  /// at `arcEnd`. The curves follow a path in a direction determined by
  /// `clockwise` and `largeArc` in such a way that the sweep angle
2316 2317 2318
  /// is always less than 360 degrees.
  ///
  /// A simple line is appended if either either radii are zero or the last
2319
  /// point in the path is `arcEnd`. The radii are scaled to fit the last path
2320 2321
  /// point if both are greater than zero but too small to describe an arc.
  ///
2322 2323 2324 2325 2326
  void arcToPoint(Offset arcEnd, {
    Radius radius = Radius.zero,
    double rotation = 0.0,
    bool largeArc = false,
    bool clockwise = true,
2327
  }) {
2328 2329 2330 2331 2332
    assert(_offsetIsValid(arcEnd));
    assert(_radiusIsValid(radius));
    _arcToPoint(arcEnd.dx, arcEnd.dy, radius.x, radius.y, rotation,
                largeArc, clockwise);
  }
2333 2334 2335
  void _arcToPoint(double arcEndX, double arcEndY, double radiusX,
                   double radiusY, double rotation, bool largeArc,
                   bool clockwise) native 'Path_arcToPoint';
2336 2337


2338 2339
  /// Appends up to four conic curves weighted to describe an oval of `radius`
  /// and rotated by `rotation`.
2340 2341 2342 2343
  ///
  /// The last path point is described by (px, py).
  ///
  /// The first curve begins from the last point in the path and the last ends
2344 2345
  /// at `arcEndDelta.dx + px` and `arcEndDelta.dy + py`. The curves follow a
  /// path in a direction determined by `clockwise` and `largeArc`
2346 2347 2348
  /// in such a way that the sweep angle is always less than 360 degrees.
  ///
  /// A simple line is appended if either either radii are zero, or, both
2349
  /// `arcEndDelta.dx` and `arcEndDelta.dy` are zero. The radii are scaled to
2350 2351
  /// fit the last path point if both are greater than zero but too small to
  /// describe an arc.
2352 2353 2354 2355 2356
  void relativeArcToPoint(Offset arcEndDelta, {
    Radius radius = Radius.zero,
    double rotation = 0.0,
    bool largeArc = false,
    bool clockwise = true,
2357
  }) {
2358 2359 2360 2361 2362 2363 2364 2365
    assert(_offsetIsValid(arcEndDelta));
    assert(_radiusIsValid(radius));
    _relativeArcToPoint(arcEndDelta.dx, arcEndDelta.dy, radius.x, radius.y,
                        rotation, largeArc, clockwise);
  }
  void _relativeArcToPoint(double arcEndX, double arcEndY, double radiusX,
                           double radiusY, double rotation,
                           bool largeArc, bool clockwise)
2366
                           native 'Path_relativeArcToPoint';
2367

2368
  /// Adds a new sub-path that consists of four lines that outline the
H
Hixie 已提交
2369
  /// given rectangle.
2370
  void addRect(Rect rect) {
2371
    assert(_rectIsValid(rect));
2372 2373
    _addRect(rect.left, rect.top, rect.right, rect.bottom);
  }
2374
  void _addRect(double left, double top, double right, double bottom) native 'Path_addRect';
H
Hixie 已提交
2375

2376
  /// Adds a new sub-path that consists of a curve that forms the
H
Hixie 已提交
2377
  /// ellipse that fills the given rectangle.
2378 2379
  ///
  /// To add a circle, pass an appropriate rectangle as `oval`. [Rect.fromCircle]
D
Dan Field 已提交
2380
  /// can be used to easily describe the circle's center [Offset] and radius.
2381
  void addOval(Rect oval) {
2382
    assert(_rectIsValid(oval));
2383 2384
    _addOval(oval.left, oval.top, oval.right, oval.bottom);
  }
2385
  void _addOval(double left, double top, double right, double bottom) native 'Path_addOval';
H
Hixie 已提交
2386

2387
  /// Adds a new sub-path with one arc segment that consists of the arc
H
Hixie 已提交
2388 2389 2390 2391 2392 2393 2394
  /// that follows the edge of the oval bounded by the given
  /// rectangle, from startAngle radians around the oval up to
  /// startAngle + sweepAngle radians around the oval, with zero
  /// radians being the point on the right hand side of the oval that
  /// crosses the horizontal line that intersects the center of the
  /// rectangle and with positive angles going clockwise around the
  /// oval.
2395
  void addArc(Rect oval, double startAngle, double sweepAngle) {
2396
    assert(_rectIsValid(oval));
2397 2398 2399
    _addArc(oval.left, oval.top, oval.right, oval.bottom, startAngle, sweepAngle);
  }
  void _addArc(double left, double top, double right, double bottom,
2400
               double startAngle, double sweepAngle) native 'Path_addArc';
H
Hixie 已提交
2401

2402
  /// Adds a new sub-path with a sequence of line segments that connect the given
I
Ian Hickson 已提交
2403 2404 2405 2406 2407 2408
  /// points.
  ///
  /// If `close` is true, a final line segment will be added that connects the
  /// last point to the first point.
  ///
  /// The `points` argument is interpreted as offsets from the origin.
2409 2410
  void addPolygon(List<Offset> points, bool close) {
    assert(points != null); // ignore: unnecessary_null_comparison
A
Adam Barth 已提交
2411 2412
    _addPolygon(_encodePointList(points), close);
  }
2413
  void _addPolygon(Float32List points, bool close) native 'Path_addPolygon';
A
Adam Barth 已提交
2414

2415
  /// Adds a new sub-path that consists of the straight lines and
H
Hixie 已提交
2416 2417
  /// curves needed to form the rounded rectangle described by the
  /// argument.
2418
  void addRRect(RRect rrect) {
2419
    assert(_rrectIsValid(rrect));
D
Dan Field 已提交
2420
    _addRRect(rrect._value32);
2421
  }
2422
  void _addRRect(Float32List rrect) native 'Path_addRRect';
H
Hixie 已提交
2423

2424
  /// Adds a new sub-path that consists of the given `path` offset by the given
2425
  /// `offset`.
2426
  ///
2427 2428 2429
  /// If `matrix4` is specified, the path will be transformed by this matrix
  /// after the matrix is translated by the given offset. The matrix is a 4x4
  /// matrix stored in column major order.
2430 2431
  void addPath(Path path, Offset offset, {Float64List? matrix4}) {
    // ignore: unnecessary_null_comparison
2432
    assert(path != null); // path is checked on the engine side
2433
    assert(_offsetIsValid(offset));
2434 2435 2436 2437 2438 2439
    if (matrix4 != null) {
      assert(_matrix4IsValid(matrix4));
      _addPathWithMatrix(path, offset.dx, offset.dy, matrix4);
    } else {
      _addPath(path, offset.dx, offset.dy);
    }
2440
  }
2441
  void _addPath(Path path, double dx, double dy) native 'Path_addPath';
2442
  void _addPathWithMatrix(Path path, double dx, double dy, Float64List matrix) native 'Path_addPathWithMatrix';
2443

A
Adam Barth 已提交
2444
  /// Adds the given path to this path by extending the current segment of this
D
Dan Field 已提交
2445
  /// path with the first segment of the given path.
2446
  ///
2447 2448 2449
  /// If `matrix4` is specified, the path will be transformed by this matrix
  /// after the matrix is translated by the given `offset`.  The matrix is a 4x4
  /// matrix stored in column major order.
2450 2451
  void extendWithPath(Path path, Offset offset, {Float64List? matrix4}) {
    // ignore: unnecessary_null_comparison
2452
    assert(path != null); // path is checked on the engine side
2453
    assert(_offsetIsValid(offset));
2454 2455 2456 2457 2458 2459
    if (matrix4 != null) {
      assert(_matrix4IsValid(matrix4));
      _extendWithPathAndMatrix(path, offset.dx, offset.dy, matrix4);
    } else {
      _extendWithPath(path, offset.dx, offset.dy);
    }
2460
  }
2461
  void _extendWithPath(Path path, double dx, double dy) native 'Path_extendWithPath';
2462
  void _extendWithPathAndMatrix(Path path, double dx, double dy, Float64List matrix) native 'Path_extendWithPathAndMatrix';
A
Adam Barth 已提交
2463

2464 2465
  /// Closes the last sub-path, as if a straight line had been drawn
  /// from the current point to the first point of the sub-path.
2466
  void close() native 'Path_close';
H
Hixie 已提交
2467

2468
  /// Clears the [Path] object of all sub-paths, returning it to the
H
Hixie 已提交
2469 2470
  /// same state it had when it was created. The _current point_ is
  /// reset to the origin.
2471
  void reset() native 'Path_reset';
H
Hixie 已提交
2472

I
Ian Hickson 已提交
2473 2474 2475 2476 2477
  /// Tests to see if the given point is within the path. (That is, whether the
  /// point would be in the visible portion of the path if the path was used
  /// with [Canvas.clipPath].)
  ///
  /// The `point` argument is interpreted as an offset from the origin.
2478 2479
  ///
  /// Returns true if the point is in the path, and false otherwise.
2480
  bool contains(Offset point) {
2481
    assert(_offsetIsValid(point));
2482 2483
    return _contains(point.dx, point.dy);
  }
2484
  bool _contains(double x, double y) native 'Path_contains';
2485

H
Hixie 已提交
2486
  /// Returns a copy of the path with all the segments of every
2487
  /// sub-path translated by the given offset.
2488
  Path shift(Offset offset) {
2489
    assert(_offsetIsValid(offset));
2490 2491 2492
    final Path path = Path._();
    _shift(path, offset.dx, offset.dy);
    return path;
2493
  }
2494
  void _shift(Path outPath, double dx, double dy) native 'Path_shift';
A
Adam Barth 已提交
2495 2496

  /// Returns a copy of the path with all the segments of every
2497
  /// sub-path transformed by the given matrix.
2498
  Path transform(Float64List matrix4) {
2499
    assert(_matrix4IsValid(matrix4));
2500 2501 2502
    final Path path = Path._();
    _transform(path, matrix4);
    return path;
A
Adam Barth 已提交
2503
  }
2504
  void _transform(Path outPath, Float64List matrix4) native 'Path_transform';
2505 2506

  /// Computes the bounding rectangle for this path.
2507
  ///
2508 2509 2510 2511
  /// A path containing only axis-aligned points on the same straight line will
  /// have no area, and therefore `Rect.isEmpty` will return true for such a
  /// path. Consider checking `rect.width + rect.height > 0.0` instead, or
  /// using the [computeMetrics] API to check the path length.
2512
  ///
2513 2514 2515
  /// For many more elaborate paths, the bounds may be inaccurate.  For example,
  /// when a path contains a circle, the points used to compute the bounds are
  /// the circle's implied control points, which form a square around the circle;
2516
  /// if the circle has a transformation applied using [transform] then that
2517 2518 2519 2520
  /// square is rotated, and the (axis-aligned, non-rotated) bounding box
  /// therefore ends up grossly overestimating the actual area covered by the
  /// circle.
  // see https://skia.org/user/api/SkPath_Reference#SkPath_getBounds
2521
  Rect getBounds() {
2522
    final Float32List rect = _getBounds();
D
Dan Field 已提交
2523
    return Rect.fromLTRB(rect[0], rect[1], rect[2], rect[3]);
2524 2525 2526
  }
  Float32List _getBounds() native 'Path_getBounds';

2527
  /// Combines the two paths according to the manner specified by the given
2528
  /// `operation`.
2529
  ///
2530 2531 2532
  /// The resulting path will be constructed from non-overlapping contours. The
  /// curve order is reduced where possible so that cubics may be turned into
  /// quadratics, and quadratics maybe turned into lines.
2533 2534 2535
  static Path combine(PathOperation operation, Path path1, Path path2) {
    assert(path1 != null); // ignore: unnecessary_null_comparison
    assert(path2 != null); // ignore: unnecessary_null_comparison
D
Dan Field 已提交
2536
    final Path path = Path();
2537 2538
    if (path._op(path1, path2, operation.index)) {
      return path;
2539
    }
D
Dan Field 已提交
2540
    throw StateError('Path.combine() failed.  This may be due an invalid path; in particular, check for NaN values.');
2541
  }
2542
  bool _op(Path path1, Path path2, int operation) native 'Path_op';
2543

2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
  /// Creates a [PathMetrics] object for this path, which can describe various
  /// properties about the contours of the path.
  ///
  /// A [Path] is made up of zero or more contours. A contour is made up of
  /// connected curves and segments, created via methods like [lineTo],
  /// [cubicTo], [arcTo], [quadraticBezierTo], their relative counterparts, as
  /// well as the add* methods such as [addRect]. Creating a new [Path] starts
  /// a new contour once it has any drawing instructions, and another new
  /// contour is started for each [moveTo] instruction.
  ///
  /// A [PathMetric] object describes properties of an individual contour,
  /// such as its length, whether it is closed, what the tangent vector of a
  /// particular offset along the path is. It also provides a method for
  /// creating sub-paths: [PathMetric.extractPath].
  ///
  /// Calculating [PathMetric] objects is not trivial. The [PathMetrics] object
  /// returned by this method is a lazy [Iterable], meaning it only performs
  /// calculations when the iterator is moved to the next [PathMetric]. Callers
  /// that wish to memoize this iterable can easily do so by using
  /// [Iterable.toList] on the result of this method. In particular, callers
  /// looking for information about how many contours are in the path should
  /// either store the result of `path.computeMetrics().length`, or should use
  /// `path.computeMetrics().toList()` so they can repeatedly check the length,
  /// since calling `Iterable.length` causes traversal of the entire iterable.
  ///
  /// In particular, callers should be aware that [PathMetrics.length] is the
  /// number of contours, **not the length of the path**. To get the length of
  /// a contour in a path, use [PathMetric.length].
2572
  ///
2573 2574
  /// If `forceClosed` is set to true, the contours of the path will be measured
  /// as if they had been closed, even if they were not explicitly closed.
2575
  PathMetrics computeMetrics({bool forceClosed = false}) {
D
Dan Field 已提交
2576
    return PathMetrics._(this, forceClosed);
2577 2578 2579 2580
  }
}

/// The geometric description of a tangent: the angle at a point.
2581
///
2582 2583 2584 2585
/// See also:
///  * [PathMetric.getTangentForOffset], which returns the tangent of an offset along a path.
class Tangent {
  /// Creates a [Tangent] with the given values.
2586
  ///
2587
  /// The arguments must not be null.
2588
  const Tangent(this.position, this.vector)
2589 2590
    : assert(position != null), // ignore: unnecessary_null_comparison
      assert(vector != null); // ignore: unnecessary_null_comparison
2591 2592

  /// Creates a [Tangent] based on the angle rather than the vector.
2593
  ///
2594 2595
  /// The [vector] is computed to be the unit vector at the given angle, interpreted
  /// as clockwise radians from the x axis.
2596
  factory Tangent.fromAngle(Offset position, double angle) {
D
Dan Field 已提交
2597
    return Tangent(position, Offset(math.cos(angle), math.sin(angle)));
2598 2599 2600
  }

  /// Position of the tangent.
2601
  ///
2602 2603
  /// When used with [PathMetric.getTangentForOffset], this represents the precise
  /// position that the given offset along the path corresponds to.
2604
  final Offset position;
2605 2606

  /// The vector of the curve at [position].
2607
  ///
2608 2609 2610
  /// When used with [PathMetric.getTangentForOffset], this is the vector of the
  /// curve that is at the given offset along the path (i.e. the direction of the
  /// curve at [position]).
2611
  final Offset vector;
2612 2613

  /// The direction of the curve at [position].
2614
  ///
2615 2616 2617
  /// When used with [PathMetric.getTangentForOffset], this is the angle of the
  /// curve that is the given offset along the path (i.e. the direction of the
  /// curve at [position]).
2618 2619
  ///
  /// This value is in radians, with 0.0 meaning pointing along the x axis in
2620 2621
  /// the positive x-axis direction, positive numbers pointing downward toward
  /// the negative y-axis, i.e. in a clockwise direction, and negative numbers
2622
  /// pointing upward toward the positive y-axis, i.e. in a counter-clockwise
2623 2624
  /// direction.
  // flip the sign to be consistent with [Path.arcTo]'s `sweepAngle`
2625
  double get angle => -math.atan2(vector.dy, vector.dx);
2626 2627 2628
}

/// An iterable collection of [PathMetric] objects describing a [Path].
2629
///
2630
/// A [PathMetrics] object is created by using the [Path.computeMetrics] method,
2631
/// and represents the path as it stood at the time of the call. Subsequent
2632
/// modifications of the path do not affect the [PathMetrics] object.
2633
///
2634
/// Each path metric corresponds to a segment, or contour, of a path.
2635 2636 2637
///
/// For example, a path consisting of a [Path.lineTo], a [Path.moveTo], and
/// another [Path.lineTo] will contain two contours and thus be represented by
2638 2639
/// two [PathMetric] objects.
///
2640 2641 2642
/// This iterable does not memoize. Callers who need to traverse the list
/// multiple times, or who need to randomly access elements of the list, should
/// use [toList] on this object.
2643
class PathMetrics extends collection.IterableBase<PathMetric> {
2644
  PathMetrics._(Path path, bool forceClosed) :
D
Dan Field 已提交
2645
    _iterator = PathMetricIterator._(_PathMeasure(path, forceClosed));
2646

2647
  final Iterator<PathMetric> _iterator;
2648 2649

  @override
2650
  Iterator<PathMetric> get iterator => _iterator;
2651 2652
}

2653 2654
/// Used by [PathMetrics] to track iteration from one segment of a path to the
/// next for measurement.
2655
class PathMetricIterator implements Iterator<PathMetric> {
2656
  PathMetricIterator._(this._pathMeasure) : assert(_pathMeasure != null); // ignore: unnecessary_null_comparison
2657

2658 2659
  PathMetric? _pathMetric;
  _PathMeasure _pathMeasure;
2660 2661

  @override
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
  PathMetric get current {
    final PathMetric? currentMetric = _pathMetric;
    if (currentMetric == null) {
      throw RangeError(
        'PathMetricIterator is not pointing to a PathMetric. This can happen in two situations:\n'
        '- The iteration has not started yet. If so, call "moveNext" to start iteration.'
        '- The iterator ran out of elements. If so, check that "moveNext" returns true prior to calling "current".'
      );
    }
    return currentMetric;
  }
2673 2674

  @override
2675
  bool moveNext() {
D
Dan Field 已提交
2676 2677
    if (_pathMeasure._nextContour()) {
      _pathMetric = PathMetric._(_pathMeasure);
2678
      return true;
2679
    }
2680 2681 2682 2683 2684
    _pathMetric = null;
    return false;
  }
}

2685
/// Utilities for measuring a [Path] and extracting sub-paths.
2686 2687
///
/// Iterate over the object returned by [Path.computeMetrics] to obtain
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
/// [PathMetric] objects. Callers that want to randomly access elements or
/// iterate multiple times should use `path.computeMetrics().toList()`, since
/// [PathMetrics] does not memoize.
///
/// Once created, the metrics are only valid for the path as it was specified
/// when [Path.computeMetrics] was called. If additional contours are added or
/// any contours are updated, the metrics need to be recomputed. Previously
/// created metrics will still refer to a snapshot of the path at the time they
/// were computed, rather than to the actual metrics for the new mutations to
/// the path.
D
Dan Field 已提交
2698 2699
class PathMetric {
  PathMetric._(this._measure)
2700
    : assert(_measure != null), // ignore: unnecessary_null_comparison
2701 2702
      length = _measure.length(_measure.currentContourIndex),
      isClosed = _measure.isClosed(_measure.currentContourIndex),
D
Dan Field 已提交
2703
      contourIndex = _measure.currentContourIndex;
2704 2705

  /// Return the total length of the current contour.
2706
  final double length;
D
Dan Field 已提交
2707 2708 2709 2710

  /// Whether the contour is closed.
  ///
  /// Returns true if the contour ends with a call to [Path.close] (which may
2711 2712 2713
  /// have been implied when using methods like [Path.addRect]) or if
  /// `forceClosed` was specified as true in the call to [Path.computeMetrics].
  /// Returns false otherwise.
2714
  final bool isClosed;
D
Dan Field 已提交
2715 2716 2717 2718 2719 2720 2721 2722 2723

  /// The zero-based index of the contour.
  ///
  /// [Path] objects are made up of zero or more contours. The first contour is
  /// created once a drawing command (e.g. [Path.lineTo]) is issued. A
  /// [Path.moveTo] command after a drawing command may create a new contour,
  /// although it may not if optimizations are applied that determine the move
  /// command did not actually result in moving the pen.
  ///
2724 2725 2726 2727
  /// This property is only valid with reference to its original iterator and
  /// the contours of the path at the time the path's metrics were computed. If
  /// additional contours were added or existing contours updated, this metric
  /// will be invalid for the current state of the path.
2728
  final int contourIndex;
D
Dan Field 已提交
2729

2730
  final _PathMeasure _measure;
D
Dan Field 已提交
2731

2732

2733
  /// Computes the position of the current contour at the given offset, and the
2734
  /// angle of the path at that point.
2735 2736
  ///
  /// For example, calling this method with a distance of 1.41 for a line from
2737 2738
  /// 0.0,0.0 to 2.0,2.0 would give a point 1.0,1.0 and the angle 45 degrees
  /// (but in radians).
2739
  ///
2740
  /// Returns null if the contour has zero [length].
2741
  ///
2742
  /// The distance is clamped to the [length] of the current contour.
2743
  Tangent? getTangentForOffset(double distance) {
2744
    return _measure.getTangentForOffset(contourIndex, distance);
D
Dan Field 已提交
2745 2746 2747 2748
  }

  /// Given a start and stop distance, return the intervening segment(s).
  ///
2749
  /// `start` and `end` are clamped to legal values (0..[length])
D
Dan Field 已提交
2750 2751
  /// Returns null if the segment is 0 length or `start` > `stop`.
  /// Begin the segment with a moveTo if `startWithMoveTo` is true.
2752
  Path? extractPath(double start, double end, {bool startWithMoveTo = true}) {
2753
    return _measure.extractPath(contourIndex, start, end, startWithMoveTo: startWithMoveTo);
D
Dan Field 已提交
2754 2755 2756
  }

  @override
2757
  String toString() => '$runtimeType{length: $length, isClosed: $isClosed, contourIndex:$contourIndex}';
D
Dan Field 已提交
2758 2759 2760 2761 2762 2763 2764 2765
}

class _PathMeasure extends NativeFieldWrapperClass2 {
  _PathMeasure(Path path, bool forceClosed) {
    _constructor(path, forceClosed);
  }
  void _constructor(Path path, bool forceClosed) native 'PathMeasure_constructor';

2766 2767 2768 2769 2770
  double length(int contourIndex) {
    assert(contourIndex <= currentContourIndex, 'Iterator must be advanced before index $contourIndex can be used.');
    return _length(contourIndex);
  }
  double _length(int contourIndex) native 'PathMeasure_getLength';
D
Dan Field 已提交
2771

2772
  Tangent? getTangentForOffset(int contourIndex, double distance) {
2773 2774
    assert(contourIndex <= currentContourIndex, 'Iterator must be advanced before index $contourIndex can be used.');
    final Float32List posTan = _getPosTan(contourIndex, distance);
2775 2776 2777 2778
    // first entry == 0 indicates that Skia returned false
    if (posTan[0] == 0.0) {
      return null;
    } else {
D
Dan Field 已提交
2779 2780 2781
      return Tangent(
        Offset(posTan[1], posTan[2]),
        Offset(posTan[3], posTan[4])
2782 2783 2784
      );
    }
  }
2785
  Float32List _getPosTan(int contourIndex, double distance) native 'PathMeasure_getPosTan';
2786

D
Dan Field 已提交
2787
  Path extractPath(int contourIndex, double start, double end, {bool startWithMoveTo = true}) {
2788
    assert(contourIndex <= currentContourIndex, 'Iterator must be advanced before index $contourIndex can be used.');
2789 2790 2791
    final Path path = Path._();
    _extractPath(path, contourIndex, start, end, startWithMoveTo: startWithMoveTo);
    return path;
2792
  }
2793
  void _extractPath(Path outPath, int contourIndex, double start, double end, {bool startWithMoveTo = true}) native 'PathMeasure_getSegment';
2794

2795 2796 2797 2798 2799
  bool isClosed(int contourIndex) {
    assert(contourIndex <= currentContourIndex, 'Iterator must be advanced before index $contourIndex can be used.');
    return _isClosed(contourIndex);
  }
  bool _isClosed(int contourIndex) native 'PathMeasure_isClosed';
2800 2801 2802 2803 2804

  // Move to the next contour in the path.
  //
  // A path can have a next contour if [Path.moveTo] was called after drawing began.
  // Return true if one exists, or false.
D
Dan Field 已提交
2805 2806 2807 2808 2809 2810 2811 2812 2813
  bool _nextContour() {
    final bool next = _nativeNextContour();
    if (next) {
      currentContourIndex++;
    }
    return next;
  }
  bool _nativeNextContour() native 'PathMeasure_nextContour';

2814 2815 2816 2817
  /// The index of the current contour in the list of contours in the path.
  ///
  /// [nextContour] will increment this to the zero based index.
  int currentContourIndex = -1;
A
Adam Barth 已提交
2818 2819
}

H
Hixie 已提交
2820
/// Styles to use for blurs in [MaskFilter] objects.
2821
// These enum values must be kept in sync with SkBlurStyle.
2822
enum BlurStyle {
H
Hixie 已提交
2823 2824
  // These mirror SkBlurStyle and must be kept in sync.

2825
  /// Fuzzy inside and outside. This is useful for painting shadows that are
2826
  /// offset from the shape that ostensibly is casting the shadow.
A
Adam Barth 已提交
2827 2828
  normal,

2829 2830 2831
  /// Solid inside, fuzzy outside. This corresponds to drawing the shape, and
  /// additionally drawing the blur. This can make objects appear brighter,
  /// maybe even as if they were fluorescent.
A
Adam Barth 已提交
2832 2833
  solid,

2834 2835 2836
  /// Nothing inside, fuzzy outside. This is useful for painting shadows for
  /// partially transparent shapes, when they are painted separately but without
  /// an offset, so that the shadow doesn't paint below the shape.
A
Adam Barth 已提交
2837 2838
  outer,

2839 2840
  /// Fuzzy inside, nothing outside. This can make shapes appear to be lit from
  /// within.
A
Adam Barth 已提交
2841
  inner,
2842 2843
}

2844 2845 2846 2847 2848
/// A mask filter to apply to shapes as they are painted. A mask filter is a
/// function that takes a bitmap of color pixels, and returns another bitmap of
/// color pixels.
///
/// Instances of this class are used with [Paint.maskFilter] on [Paint] objects.
2849
class MaskFilter {
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
  /// Creates a mask filter that takes the shape being drawn and blurs it.
  ///
  /// This is commonly used to approximate shadows.
  ///
  /// The `style` argument controls the kind of effect to draw; see [BlurStyle].
  ///
  /// The `sigma` argument controls the size of the effect. It is the standard
  /// deviation of the Gaussian blur to apply. The value must be greater than
  /// zero. The sigma corresponds to very roughly half the radius of the effect
  /// in pixels.
  ///
2861
  /// A blur is an expensive operation and should therefore be used sparingly.
2862 2863 2864 2865 2866 2867 2868 2869 2870
  ///
  /// The arguments must not be null.
  ///
  /// See also:
  ///
  ///  * [Canvas.drawShadow], which is a more efficient way to draw shadows.
  const MaskFilter.blur(
    this._style,
    this._sigma,
2871 2872
  ) : assert(_style != null), // ignore: unnecessary_null_comparison
      assert(_sigma != null); // ignore: unnecessary_null_comparison
2873

2874 2875
  final BlurStyle _style;
  final double _sigma;
2876 2877 2878 2879 2880 2881 2882

  // The type of MaskFilter class to create for Skia.
  // These constants must be kept in sync with MaskFilterType in paint.cc.
  static const int _TypeNone = 0; // null
  static const int _TypeBlur = 1; // SkBlurMaskFilter

  @override
A
Alexandre Ardhuin 已提交
2883
  bool operator ==(Object other) {
2884 2885 2886
    return other is MaskFilter
        && other._style == _style
        && other._sigma == _sigma;
2887
  }
2888 2889

  @override
2890
  int get hashCode => hashValues(_style, _sigma);
2891 2892

  @override
2893
  String toString() => 'MaskFilter.blur($_style, ${_sigma.toStringAsFixed(1)})';
2894 2895
}

2896 2897 2898 2899 2900
/// A description of a color filter to apply when drawing a shape or compositing
/// a layer with a particular [Paint]. A color filter is a function that takes
/// two colors, and outputs one color. When applied during compositing, it is
/// independently applied to each pixel of the layer being drawn before the
/// entire layer is merged with the destination.
H
Hixie 已提交
2901
///
2902 2903
/// Instances of this class are used with [Paint.colorFilter] on [Paint]
/// objects.
2904
class ColorFilter {
2905
  /// Creates a color filter that applies the blend mode given as the second
2906 2907 2908 2909
  /// argument. The source color is the one given as the first argument, and the
  /// destination color is the one from the layer being composited.
  ///
  /// The output of this filter is then composited into the background according
2910
  /// to the [Paint.blendMode], using the output of this filter as the source
2911
  /// and the background as the destination.
2912
  const ColorFilter.mode(Color color, BlendMode blendMode)
D
Dan Field 已提交
2913
      : _color = color,
2914 2915 2916 2917
        _blendMode = blendMode,
        _matrix = null,
        _type = _TypeMode;

D
Dan Field 已提交
2918 2919
  /// Construct a color filter that transforms a color by a 5x5 matrix, where
  /// the fifth row is implicitly added in an identity configuration.
D
Dan Field 已提交
2920 2921 2922 2923
  ///
  /// Every pixel's color value, repsented as an `[R, G, B, A]`, is matrix
  /// multiplied to create a new color:
  ///
D
Dan Field 已提交
2924
  /// ```text
D
Dan Field 已提交
2925
  /// | R' |   | a00 a01 a02 a03 a04 |   | R |
D
Dan Field 已提交
2926 2927
  /// | G' |   | a10 a11 a22 a33 a44 |   | G |
  /// | B' | = | a20 a21 a22 a33 a44 | * | B |
D
Dan Field 已提交
2928
  /// | A' |   | a30 a31 a22 a33 a44 |   | A |
D
Dan Field 已提交
2929
  /// | 1  |   |  0   0   0   0   1  |   | 1 |
D
Dan Field 已提交
2930 2931 2932 2933 2934 2935
  /// ```
  ///
  /// The matrix is in row-major order and the translation column is specified
  /// in unnormalized, 0...255, space. For example, the identity matrix is:
  ///
  /// ```
2936
  /// const ColorFilter identity = ColorFilter.matrix(<double>[
D
Dan Field 已提交
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
  ///   1, 0, 0, 0, 0,
  ///   0, 1, 0, 0, 0,
  ///   0, 0, 1, 0, 0,
  ///   0, 0, 0, 1, 0,
  /// ]);
  /// ```
  ///
  /// ## Examples
  ///
  /// An inversion color matrix:
  ///
  /// ```
  /// const ColorFilter invert = ColorFilter.matrix(<double>[
  ///   -1,  0,  0, 0, 255,
  ///    0, -1,  0, 0, 255,
  ///    0,  0, -1, 0, 255,
  ///    0,  0,  0, 1,   0,
  /// ]);
  /// ```
  ///
  /// A sepia-toned color matrix (values based on the [Filter Effects Spec](https://www.w3.org/TR/filter-effects-1/#sepiaEquivalent)):
  ///
  /// ```
  /// const ColorFilter sepia = ColorFilter.matrix(<double>[
  ///   0.393, 0.769, 0.189, 0, 0,
  ///   0.349, 0.686, 0.168, 0, 0,
  ///   0.272, 0.534, 0.131, 0, 0,
  ///   0,     0,     0,     1, 0,
  /// ]);
  /// ```
  ///
  /// A greyscale color filter (values based on the [Filter Effects Spec](https://www.w3.org/TR/filter-effects-1/#grayscaleEquivalent)):
  ///
  /// ```
  /// const ColorFilter greyscale = ColorFilter.matrix(<double>[
  ///   0.2126, 0.7152, 0.0722, 0, 0,
  ///   0.2126, 0.7152, 0.0722, 0, 0,
  ///   0.2126, 0.7152, 0.0722, 0, 0,
  ///   0,      0,      0,      1, 0,
  /// ]);
  /// ```
2978
  const ColorFilter.matrix(List<double> matrix)
D
Dan Field 已提交
2979
      : _color = null,
2980 2981 2982 2983
        _blendMode = null,
        _matrix = matrix,
        _type = _TypeMatrix;

2984
  /// Construct a color filter that applies the sRGB gamma curve to the RGB
2985 2986 2987 2988 2989 2990 2991
  /// channels.
  const ColorFilter.linearToSrgbGamma()
      : _color = null,
        _blendMode = null,
        _matrix = null,
        _type = _TypeLinearToSrgbGamma;

2992
  /// Creates a color filter that applies the inverse of the sRGB gamma curve
2993 2994 2995 2996 2997 2998
  /// to the RGB channels.
  const ColorFilter.srgbToLinearGamma()
      : _color = null,
        _blendMode = null,
        _matrix = null,
        _type = _TypeSrgbToLinearGamma;
2999

3000 3001 3002
  final Color? _color;
  final BlendMode? _blendMode;
  final List<double>? _matrix;
3003 3004 3005 3006 3007 3008 3009
  final int _type;

  // The type of SkColorFilter class to create for Skia.
  static const int _TypeMode = 1; // MakeModeFilter
  static const int _TypeMatrix = 2; // MakeMatrixFilterRowMajor255
  static const int _TypeLinearToSrgbGamma = 3; // MakeLinearToSRGBGamma
  static const int _TypeSrgbToLinearGamma = 4; // MakeSRGBToLinearGamma
3010 3011

  @override
A
Alexandre Ardhuin 已提交
3012
  bool operator ==(Object other) {
3013 3014 3015 3016 3017
    return other is ColorFilter
        && other._type == _type
        && _listEquals<double>(other._matrix, _matrix)
        && other._color == _color
        && other._blendMode == _blendMode;
3018 3019
  }

3020
  _ColorFilter? _toNativeColorFilter() {
3021 3022
    switch (_type) {
      case _TypeMode:
D
Dan Field 已提交
3023 3024 3025
        if (_color == null || _blendMode == null) {
          return null;
        }
3026 3027
        return _ColorFilter.mode(this);
      case _TypeMatrix:
D
Dan Field 已提交
3028 3029 3030
        if (_matrix == null) {
          return null;
        }
3031
        assert(_matrix!.length == 20, 'Color Matrix must have 20 entries.');
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
        return _ColorFilter.matrix(this);
      case _TypeLinearToSrgbGamma:
        return _ColorFilter.linearToSrgbGamma(this);
      case _TypeSrgbToLinearGamma:
        return _ColorFilter.srgbToLinearGamma(this);
      default:
        throw StateError('Unknown mode $_type for ColorFilter.');
    }
  }

3042
  @override
3043
  int get hashCode => hashValues(_color, _blendMode, hashList(_matrix), _type);
3044 3045

  @override
3046
  String toString() {
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
    switch (_type) {
      case _TypeMode:
        return 'ColorFilter.mode($_color, $_blendMode)';
      case _TypeMatrix:
        return 'ColorFilter.matrix($_matrix)';
      case _TypeLinearToSrgbGamma:
        return 'ColorFilter.linearToSrgbGamma()';
      case _TypeSrgbToLinearGamma:
        return 'ColorFilter.srgbToLinearGamma()';
      default:
        return 'Unknown ColorFilter type. This is an error. If you\'re seeing this, please file an issue at https://github.com/flutter/flutter/issues/new.';
    }
  }
3060
}
A
Adam Barth 已提交
3061

3062 3063 3064 3065 3066
/// A [ColorFilter] that is backed by a native SkColorFilter.
///
/// This is a private class, rather than being the implementation of the public
/// ColorFilter, because we want ColorFilter to be const constructible and
/// efficiently comparable, so that widgets can check for ColorFilter equality to
J
Jim Graham 已提交
3067
/// avoid repainting.
3068 3069
class _ColorFilter extends NativeFieldWrapperClass2 {
  _ColorFilter.mode(this.creator)
3070
    : assert(creator != null), // ignore: unnecessary_null_comparison
3071 3072
      assert(creator._type == ColorFilter._TypeMode) {
    _constructor();
3073
    _initMode(creator._color!.value, creator._blendMode!.index);
3074 3075 3076
  }

  _ColorFilter.matrix(this.creator)
3077
    : assert(creator != null), // ignore: unnecessary_null_comparison
3078 3079
      assert(creator._type == ColorFilter._TypeMatrix) {
    _constructor();
3080
    _initMatrix(Float32List.fromList(creator._matrix!));
3081 3082
  }
  _ColorFilter.linearToSrgbGamma(this.creator)
3083
    : assert(creator != null), // ignore: unnecessary_null_comparison
3084 3085 3086 3087 3088 3089
      assert(creator._type == ColorFilter._TypeLinearToSrgbGamma) {
    _constructor();
    _initLinearToSrgbGamma();
  }

  _ColorFilter.srgbToLinearGamma(this.creator)
3090
    : assert(creator != null), // ignore: unnecessary_null_comparison
3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
      assert(creator._type == ColorFilter._TypeSrgbToLinearGamma) {
    _constructor();
    _initSrgbToLinearGamma();
  }

  /// The original Dart object that created the native wrapper, which retains
  /// the values used for the filter.
  final ColorFilter creator;

  void _constructor() native 'ColorFilter_constructor';
  void _initMode(int color, int blendMode) native 'ColorFilter_initMode';
  void _initMatrix(Float32List matrix) native 'ColorFilter_initMatrix';
  void _initLinearToSrgbGamma() native 'ColorFilter_initLinearToSrgbGamma';
  void _initSrgbToLinearGamma() native 'ColorFilter_initSrgbToLinearGamma';
}

3107 3108
/// A filter operation to apply to a raster image.
///
3109 3110 3111
/// See also:
///
///  * [BackdropFilter], a widget that applies [ImageFilter] to its rendering.
3112
///  * [ImageFiltered], a widget that applies [ImageFilter] to its children.
3113
///  * [SceneBuilder.pushBackdropFilter], which is the low-level API for using
3114 3115 3116
///    this class as a backdrop filter.
///  * [SceneBuilder.pushImageFilter], which is the low-level API for using
///    this class as a child layer filter.
J
Jim Graham 已提交
3117 3118
class ImageFilter {
  /// Creates an image filter that applies a Gaussian blur.
3119 3120 3121 3122
  ImageFilter.blur({ double sigmaX = 0.0, double sigmaY = 0.0 })
      : assert(sigmaX != null), // ignore: unnecessary_null_comparison
        assert(sigmaY != null), // ignore: unnecessary_null_comparison
        _data = _makeList(sigmaX, sigmaY),
J
Jim Graham 已提交
3123 3124 3125 3126 3127 3128 3129
        _filterQuality = null,
        _type = _kTypeBlur;

  /// Creates an image filter that applies a matrix transformation.
  ///
  /// For example, applying a positive scale matrix (see [Matrix4.diagonal3])
  /// when used with [BackdropFilter] would magnify the background image.
3130 3131 3132 3133
  ImageFilter.matrix(Float64List matrix4,
                     { FilterQuality filterQuality = FilterQuality.low })
      : assert(matrix4 != null), // ignore: unnecessary_null_comparison
        _data = Float64List.fromList(matrix4),
J
Jim Graham 已提交
3134 3135 3136 3137 3138 3139 3140 3141
        _filterQuality = filterQuality,
        _type = _kTypeMatrix {
    if (matrix4.length != 16)
      throw ArgumentError('"matrix4" must have 16 entries.');
  }

  static Float64List _makeList(double a, double b) {
    final Float64List list = Float64List(2);
3142 3143
    list[0] = a;
    list[1] = b;
J
Jim Graham 已提交
3144 3145 3146
    return list;
  }

3147 3148 3149 3150
  final Float64List _data;
  final FilterQuality? _filterQuality;
  final int _type;
  _ImageFilter? _nativeFilter;
J
Jim Graham 已提交
3151 3152 3153 3154 3155 3156

  // The type of SkImageFilter class to create for Skia.
  static const int _kTypeBlur = 0;   // MakeBlurFilter
  static const int _kTypeMatrix = 1; // MakeMatrixFilterRowMajor255

  @override
A
Alexandre Ardhuin 已提交
3157
  bool operator ==(Object other) {
3158 3159 3160 3161
    return other is ImageFilter
        && other._type == _type
        && _listEquals<double>(other._data, _data)
        && other._filterQuality == _filterQuality;
J
Jim Graham 已提交
3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
  }

  _ImageFilter _toNativeImageFilter() => _nativeFilter ??= _makeNativeImageFilter();

  _ImageFilter _makeNativeImageFilter() {
    switch (_type) {
      case _kTypeBlur:
        return _ImageFilter.blur(this);
      case _kTypeMatrix:
        return _ImageFilter.matrix(this);
      default:
        throw StateError('Unknown mode $_type for ImageFilter.');
    }
  }

  @override
3178
  int get hashCode => hashValues(_filterQuality, hashList(_data), _type);
J
Jim Graham 已提交
3179 3180

  @override
3181
  String toString() {
J
Jim Graham 已提交
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198
    switch (_type) {
      case _kTypeBlur:
        return 'ImageFilter.blur(${_data[0]}, ${_data[1]})';
      case _kTypeMatrix:
        return 'ImageFilter.matrix($_data, $_filterQuality)';
      default:
        return 'Unknown ImageFilter type. This is an error. If you\'re seeing this, please file an issue at https://github.com/flutter/flutter/issues/new.';
    }
  }
}

/// An [ImageFilter] that is backed by a native SkImageFilter.
///
/// This is a private class, rather than being the implementation of the public
/// ImageFilter, because we want ImageFilter to be efficiently comparable, so that
/// widgets can check for ImageFilter equality to avoid repainting.
class _ImageFilter extends NativeFieldWrapperClass2 {
3199
  void _constructor() native 'ImageFilter_constructor';
3200

3201
  /// Creates an image filter that applies a Gaussian blur.
J
Jim Graham 已提交
3202
  _ImageFilter.blur(this.creator)
3203
    : assert(creator != null), // ignore: unnecessary_null_comparison
J
Jim Graham 已提交
3204
      assert(creator._type == ImageFilter._kTypeBlur) {
3205
    _constructor();
J
Jim Graham 已提交
3206
    _initBlur(creator._data[0], creator._data[1]);
3207
  }
3208
  void _initBlur(double sigmaX, double sigmaY) native 'ImageFilter_initBlur';
3209 3210 3211

  /// Creates an image filter that applies a matrix transformation.
  ///
3212
  /// For example, applying a positive scale matrix (see [Matrix4.diagonal3])
3213
  /// when used with [BackdropFilter] would magnify the background image.
J
Jim Graham 已提交
3214
  _ImageFilter.matrix(this.creator)
3215
    : assert(creator != null), // ignore: unnecessary_null_comparison
J
Jim Graham 已提交
3216 3217
      assert(creator._type == ImageFilter._kTypeMatrix) {
    if (creator._data.length != 16)
D
Dan Field 已提交
3218
      throw ArgumentError('"matrix4" must have 16 entries.');
3219
    _constructor();
3220
    _initMatrix(creator._data, creator._filterQuality!.index);
3221 3222
  }
  void _initMatrix(Float64List matrix4, int filterQuality) native 'ImageFilter_initMatrix';
J
Jim Graham 已提交
3223 3224 3225

  /// The original Dart object that created the native wrapper, which retains
  /// the values used for the filter.
3226
  final ImageFilter creator;
3227 3228
}

H
Hixie 已提交
3229
/// Base class for objects such as [Gradient] and [ImageShader] which
3230
/// correspond to shaders as used by [Paint.shader].
3231 3232 3233
class Shader extends NativeFieldWrapperClass2 {
  /// This class is created by the engine, and should not be instantiated
  /// or extended directly.
3234
  @pragma('vm:entry-point')
3235 3236
  Shader._();
}
A
Adam Barth 已提交
3237 3238

/// Defines what happens at the edge of the gradient.
3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
///
/// A gradient is defined along a finite inner area. In the case of a linear
/// gradient, it's between the parallel lines that are orthogonal to the line
/// drawn between two points. In the case of radial gradients, it's the disc
/// that covers the circle centered on a particular point up to a given radius.
///
/// This enum is used to define how the gradient should paint the regions
/// outside that defined inner area.
///
/// See also:
///
///  * [painting.Gradient], the superclass for [LinearGradient] and
///    [RadialGradient], as used by [BoxDecoration] et al, which works in
///    relative coordinates and can create a [Shader] representing the gradient
///    for a particular [Rect] on demand.
///  * [dart:ui.Gradient], the low-level class used when dealing with the
3255 3256
///    [Paint.shader] property directly, with its [Gradient.linear] and
///    [Gradient.radial] constructors.
3257
// These enum values must be kept in sync with SkShader::TileMode.
A
Adam Barth 已提交
3258 3259
enum TileMode {
  /// Edge is clamped to the final color.
3260 3261 3262 3263
  ///
  /// The gradient will paint the all the regions outside the inner area with
  /// the color of the point closest to that region.
  ///
3264
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_clamp_radial.png)
A
Adam Barth 已提交
3265
  clamp,
3266

3267 3268 3269 3270 3271 3272
  /// Edge is repeated from first color to last.
  ///
  /// This is as if the stop points from 0.0 to 1.0 were then repeated from 1.0
  /// to 2.0, 2.0 to 3.0, and so forth (and for linear gradients, similarly from
  /// -1.0 to 0.0, -2.0 to -1.0, etc).
  ///
3273 3274
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_linear.png)
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_radial.png)
3275 3276
  repeated,

A
Adam Barth 已提交
3277
  /// Edge is mirrored from last color to first.
3278 3279 3280 3281 3282 3283
  ///
  /// This is as if the stop points from 0.0 to 1.0 were then repeated backwards
  /// from 2.0 to 1.0, then forwards from 2.0 to 3.0, then backwards again from
  /// 4.0 to 3.0, and so forth (and for linear gradients, similarly from in the
  /// negative direction).
  ///
3284 3285
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_linear.png)
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_radial.png)
3286
  mirror,
A
Adam Barth 已提交
3287 3288
}

3289
Int32List _encodeColorList(List<Color> colors) {
3290
  final int colorCount = colors.length;
D
Dan Field 已提交
3291
  final Int32List result = Int32List(colorCount);
3292 3293 3294 3295 3296
  for (int i = 0; i < colorCount; ++i)
    result[i] = colors[i].value;
  return result;
}

3297 3298
Float32List _encodePointList(List<Offset> points) {
  assert(points != null); // ignore: unnecessary_null_comparison
3299
  final int pointCount = points.length;
D
Dan Field 已提交
3300
  final Float32List result = Float32List(pointCount * 2);
3301 3302 3303
  for (int i = 0; i < pointCount; ++i) {
    final int xIndex = i * 2;
    final int yIndex = xIndex + 1;
I
Ian Hickson 已提交
3304
    final Offset point = points[i];
3305
    assert(_offsetIsValid(point));
I
Ian Hickson 已提交
3306 3307
    result[xIndex] = point.dx;
    result[yIndex] = point.dy;
3308 3309 3310 3311
  }
  return result;
}

3312
Float32List _encodeTwoPoints(Offset pointA, Offset pointB) {
3313 3314
  assert(_offsetIsValid(pointA));
  assert(_offsetIsValid(pointB));
D
Dan Field 已提交
3315
  final Float32List result = Float32List(4);
I
Ian Hickson 已提交
3316 3317 3318 3319 3320 3321 3322
  result[0] = pointA.dx;
  result[1] = pointA.dy;
  result[2] = pointB.dx;
  result[3] = pointB.dy;
  return result;
}

3323 3324
/// A shader (as used by [Paint.shader]) that renders a color gradient.
///
V
Victor Choueiri 已提交
3325 3326
/// There are several types of gradients, represented by the various constructors
/// on this class.
3327 3328 3329
///
/// See also:
///
3330
///  * [Gradient](https://api.flutter.dev/flutter/painting/Gradient-class.html), the class in the [painting] library.
3331
///
A
Adam Barth 已提交
3332
class Gradient extends Shader {
3333

3334
  void _constructor() native 'Gradient_constructor';
A
Adam Barth 已提交
3335

I
Ian Hickson 已提交
3336 3337 3338 3339 3340 3341 3342 3343
  /// Creates a linear gradient from `from` to `to`.
  ///
  /// If `colorStops` is provided, `colorStops[i]` is a number from 0.0 to 1.0
  /// that specifies where `color[i]` begins in the gradient. If `colorStops` is
  /// not provided, then only two stops, at 0.0 and 1.0, are implied (and
  /// `color` must therefore only have two entries).
  ///
  /// The behavior before `from` and after `to` is described by the `tileMode`
3344 3345
  /// argument. For details, see the [TileMode] enum.
  ///
3346 3347 3348
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_clamp_linear.png)
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_linear.png)
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_linear.png)
I
Ian Hickson 已提交
3349 3350 3351 3352
  ///
  /// If `from`, `to`, `colors`, or `tileMode` are null, or if `colors` or
  /// `colorStops` contain null values, this constructor will throw a
  /// [NoSuchMethodError].
3353 3354 3355 3356
  ///
  /// If `matrix4` is provided, the gradient fill will be transformed by the
  /// specified 4x4 matrix relative to the local coordinate system. `matrix4` must
  /// be a column-major matrix packed into a list of 16 values.
I
Ian Hickson 已提交
3357
  Gradient.linear(
3358 3359 3360 3361 3362 3363
    Offset from,
    Offset to,
    List<Color> colors, [
    List<double>? colorStops,
    TileMode tileMode = TileMode.clamp,
    Float64List? matrix4,
3364 3365
  ]) : assert(_offsetIsValid(from)),
       assert(_offsetIsValid(to)),
3366 3367 3368
       assert(colors != null), // ignore: unnecessary_null_comparison
       assert(tileMode != null), // ignore: unnecessary_null_comparison
       assert(matrix4 == null || _matrix4IsValid(matrix4)), // ignore: unnecessary_null_comparison
3369
       super._() {
A
Adam Barth 已提交
3370
    _validateColorStops(colors, colorStops);
I
Ian Hickson 已提交
3371
    final Float32List endPointsBuffer = _encodeTwoPoints(from, to);
3372
    final Int32List colorsBuffer = _encodeColorList(colors);
3373
    final Float32List? colorStopsBuffer = colorStops == null ? null : Float32List.fromList(colorStops);
3374
    _constructor();
3375
    _initLinear(endPointsBuffer, colorsBuffer, colorStopsBuffer, tileMode.index, matrix4);
A
Adam Barth 已提交
3376
  }
3377
  void _initLinear(Float32List endPoints, Int32List colors, Float32List? colorStops, int tileMode, Float64List? matrix4) native 'Gradient_initLinear';
A
Adam Barth 已提交
3378

3379
  /// Creates a radial gradient centered at `center` that ends at `radius`
I
Ian Hickson 已提交
3380 3381 3382 3383 3384 3385 3386 3387
  /// distance from the center.
  ///
  /// If `colorStops` is provided, `colorStops[i]` is a number from 0.0 to 1.0
  /// that specifies where `color[i]` begins in the gradient. If `colorStops` is
  /// not provided, then only two stops, at 0.0 and 1.0, are implied (and
  /// `color` must therefore only have two entries).
  ///
  /// The behavior before and after the radius is described by the `tileMode`
3388 3389
  /// argument. For details, see the [TileMode] enum.
  ///
3390 3391 3392
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_clamp_radial.png)
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_radial.png)
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_radial.png)
I
Ian Hickson 已提交
3393 3394 3395 3396
  ///
  /// If `center`, `radius`, `colors`, or `tileMode` are null, or if `colors` or
  /// `colorStops` contain null values, this constructor will throw a
  /// [NoSuchMethodError].
3397 3398
  ///
  /// If `matrix4` is provided, the gradient fill will be transformed by the
3399 3400
  /// specified 4x4 matrix relative to the local coordinate system. `matrix4` must
  /// be a column-major matrix packed into a list of 16 values.
3401 3402
  ///
  /// If `focal` is provided and not equal to `center` and `focalRadius` is
D
Dan Field 已提交
3403
  /// provided and not equal to 0.0, the generated shader will be a two point
3404
  /// conical radial gradient, with `focal` being the center of the focal
D
Dan Field 已提交
3405 3406 3407
  /// circle and `focalRadius` being the radius of that circle. If `focal` is
  /// provided and not equal to `center`, at least one of the two offsets must
  /// not be equal to [Offset.zero].
3408
  Gradient.radial(
3409 3410 3411 3412 3413 3414 3415 3416
    Offset center,
    double radius,
    List<Color> colors, [
    List<double>? colorStops,
    TileMode tileMode = TileMode.clamp,
    Float64List? matrix4,
    Offset? focal,
    double focalRadius = 0.0
3417
  ]) : assert(_offsetIsValid(center)),
3418 3419
       assert(colors != null), // ignore: unnecessary_null_comparison
       assert(tileMode != null), // ignore: unnecessary_null_comparison
V
Victor Choueiri 已提交
3420
       assert(matrix4 == null || _matrix4IsValid(matrix4)),
3421
       super._() {
A
Adam Barth 已提交
3422
    _validateColorStops(colors, colorStops);
3423
    final Int32List colorsBuffer = _encodeColorList(colors);
3424
    final Float32List? colorStopsBuffer = colorStops == null ? null : Float32List.fromList(colorStops);
D
Dan Field 已提交
3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435

    // If focal is null or focal radius is null, this should be treated as a regular radial gradient
    // If focal == center and the focal radius is 0.0, it's still a regular radial gradient
    if (focal == null || (focal == center && focalRadius == 0.0)) {
      _constructor();
      _initRadial(center.dx, center.dy, radius, colorsBuffer, colorStopsBuffer, tileMode.index, matrix4);
    } else {
      assert(center != Offset.zero || focal != Offset.zero); // will result in exception(s) in Skia side
      _constructor();
      _initConical(focal.dx, focal.dy, focalRadius, center.dx, center.dy, radius, colorsBuffer, colorStopsBuffer, tileMode.index, matrix4);
    }
A
Adam Barth 已提交
3436
  }
3437 3438
  void _initRadial(double centerX, double centerY, double radius, Int32List colors, Float32List? colorStops, int tileMode, Float64List? matrix4) native 'Gradient_initRadial';
  void _initConical(double startX, double startY, double startRadius, double endX, double endY, double endRadius, Int32List colors, Float32List? colorStops, int tileMode, Float64List? matrix4) native 'Gradient_initTwoPointConical';
H
Hixie 已提交
3439

V
Victor Choueiri 已提交
3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
  /// Creates a sweep gradient centered at `center` that starts at `startAngle`
  /// and ends at `endAngle`.
  ///
  /// `startAngle` and `endAngle` should be provided in radians, with zero
  /// radians being the horizontal line to the right of the `center` and with
  /// positive angles going clockwise around the `center`.
  ///
  /// If `colorStops` is provided, `colorStops[i]` is a number from 0.0 to 1.0
  /// that specifies where `color[i]` begins in the gradient. If `colorStops` is
  /// not provided, then only two stops, at 0.0 and 1.0, are implied (and
  /// `color` must therefore only have two entries).
  ///
  /// The behavior before `startAngle` and after `endAngle` is described by the
  /// `tileMode` argument. For details, see the [TileMode] enum.
  ///
3455 3456 3457
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_clamp_sweep.png)
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_sweep.png)
  /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_sweep.png)
V
Victor Choueiri 已提交
3458 3459 3460 3461 3462
  ///
  /// If `center`, `colors`, `tileMode`, `startAngle`, or `endAngle` are null,
  /// or if `colors` or `colorStops` contain null values, this constructor will
  /// throw a [NoSuchMethodError].
  ///
3463
  /// If `matrix4` is provided, the gradient fill will be transformed by the
V
Victor Choueiri 已提交
3464 3465 3466
  /// specified 4x4 matrix relative to the local coordinate system. `matrix4` must
  /// be a column-major matrix packed into a list of 16 values.
  Gradient.sweep(
3467 3468 3469
    Offset center,
    List<Color> colors, [
    List<double>? colorStops,
V
Victor Choueiri 已提交
3470
    TileMode tileMode = TileMode.clamp,
3471 3472
    double startAngle = 0.0,
    double endAngle = math.pi * 2,
3473
    Float64List? matrix4,
V
Victor Choueiri 已提交
3474
  ]) : assert(_offsetIsValid(center)),
3475 3476 3477 3478
       assert(colors != null), // ignore: unnecessary_null_comparison
       assert(tileMode != null), // ignore: unnecessary_null_comparison
       assert(startAngle != null), // ignore: unnecessary_null_comparison
       assert(endAngle != null), // ignore: unnecessary_null_comparison
V
Victor Choueiri 已提交
3479 3480 3481 3482 3483
       assert(startAngle < endAngle),
       assert(matrix4 == null || _matrix4IsValid(matrix4)),
       super._() {
    _validateColorStops(colors, colorStops);
    final Int32List colorsBuffer = _encodeColorList(colors);
3484
    final Float32List? colorStopsBuffer = colorStops == null ? null : Float32List.fromList(colorStops);
V
Victor Choueiri 已提交
3485 3486 3487
    _constructor();
    _initSweep(center.dx, center.dy, colorsBuffer, colorStopsBuffer, tileMode.index, startAngle, endAngle, matrix4);
  }
3488
  void _initSweep(double centerX, double centerY, Int32List colors, Float32List? colorStops, int tileMode, double startAngle, double endAngle, Float64List? matrix) native 'Gradient_initSweep';
V
Victor Choueiri 已提交
3489

3490
  static void _validateColorStops(List<Color> colors, List<double>? colorStops) {
I
Ian Hickson 已提交
3491 3492
    if (colorStops == null) {
      if (colors.length != 2)
D
Dan Field 已提交
3493
        throw ArgumentError('"colors" must have length 2 if "colorStops" is omitted.');
I
Ian Hickson 已提交
3494 3495
    } else {
      if (colors.length != colorStops.length)
D
Dan Field 已提交
3496
        throw ArgumentError('"colors" and "colorStops" arguments must have equal length.');
I
Ian Hickson 已提交
3497
    }
H
Hixie 已提交
3498
  }
A
Adam Barth 已提交
3499 3500
}

3501
/// A shader (as used by [Paint.shader]) that tiles an image.
A
Adam Barth 已提交
3502
class ImageShader extends Shader {
3503 3504 3505 3506 3507
  /// Creates an image-tiling shader. The first argument specifies the image to
  /// tile. The second and third arguments specify the [TileMode] for the x
  /// direction and y direction respectively. The fourth argument gives the
  /// matrix to apply to the effect. All the arguments are required and must not
  /// be null.
3508
  @pragma('vm:entry-point')
3509 3510
  ImageShader(Image image, TileMode tmx, TileMode tmy, Float64List matrix4) :
    // ignore: unnecessary_null_comparison
3511
    assert(image != null), // image is checked on the engine side
3512 3513 3514
    assert(tmx != null), // ignore: unnecessary_null_comparison
    assert(tmy != null), // ignore: unnecessary_null_comparison
    assert(matrix4 != null), // ignore: unnecessary_null_comparison
3515
    super._() {
3516
    if (matrix4.length != 16)
D
Dan Field 已提交
3517
      throw ArgumentError('"matrix4" must have 16 entries.');
H
Hixie 已提交
3518
    _constructor();
3519
    _initWithImage(image._image, tmx.index, tmy.index, matrix4);
A
Adam Barth 已提交
3520
  }
3521
  void _constructor() native 'ImageShader_constructor';
3522
  void _initWithImage(_Image image, int tmx, int tmy, Float64List matrix4) native 'ImageShader_initWithImage';
A
Adam Barth 已提交
3523 3524
}

3525
/// Defines how a list of points is interpreted when drawing a set of triangles.
A
Adam Barth 已提交
3526 3527
///
/// Used by [Canvas.drawVertices].
3528
// These enum values must be kept in sync with SkVertices::VertexMode.
3529
enum VertexMode {
A
Adam Barth 已提交
3530
  /// Draw each sequence of three points as the vertices of a triangle.
3531
  triangles,
A
Adam Barth 已提交
3532 3533

  /// Draw each sliding window of three points as the vertices of a triangle.
3534
  triangleStrip,
A
Adam Barth 已提交
3535 3536

  /// Draw the first point and each sliding window of two points as the vertices of a triangle.
3537 3538 3539
  triangleFan,
}

3540 3541
/// A set of vertex data used by [Canvas.drawVertices].
class Vertices extends NativeFieldWrapperClass2 {
3542 3543 3544 3545 3546 3547 3548 3549 3550
  /// Creates a set of vertex data for use with [Canvas.drawVertices].
  ///
  /// The [mode] and [positions] parameters must not be null.
  ///
  /// If the [textureCoordinates] or [colors] parameters are provided, they must
  /// be the same length as [positions].
  ///
  /// If the [indices] parameter is provided, all values in the list must be
  /// valid index values for [positions].
3551
  Vertices(
3552 3553 3554 3555 3556 3557 3558
    VertexMode mode,
    List<Offset> positions, {
    List<Offset>? textureCoordinates,
    List<Color>? colors,
    List<int>? indices,
  }) : assert(mode != null), // ignore: unnecessary_null_comparison
       assert(positions != null) { // ignore: unnecessary_null_comparison
3559
    if (textureCoordinates != null && textureCoordinates.length != positions.length)
D
Dan Field 已提交
3560
      throw ArgumentError('"positions" and "textureCoordinates" lengths must match.');
3561
    if (colors != null && colors.length != positions.length)
D
Dan Field 已提交
3562
      throw ArgumentError('"positions" and "colors" lengths must match.');
3563
    if (indices != null && indices.any((int i) => i < 0 || i >= positions.length))
D
Dan Field 已提交
3564
      throw ArgumentError('"indices" values must be valid indices in the positions list.');
3565

3566
    final Float32List encodedPositions = _encodePointList(positions);
3567
    final Float32List? encodedTextureCoordinates = (textureCoordinates != null)
3568 3569
      ? _encodePointList(textureCoordinates)
      : null;
3570
    final Int32List? encodedColors = colors != null
3571 3572
      ? _encodeColorList(colors)
      : null;
3573
    final Uint16List? encodedIndices = indices != null
D
Dan Field 已提交
3574
      ? Uint16List.fromList(indices)
3575
      : null;
3576

3577
    if (!_init(this, mode.index, encodedPositions, encodedTextureCoordinates, encodedColors, encodedIndices))
D
Dan Field 已提交
3578
      throw ArgumentError('Invalid configuration for vertices.');
3579 3580
  }

3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
  /// Creates a set of vertex data for use with [Canvas.drawVertices], directly
  /// using the encoding methods of [new Vertices].
  ///
  /// The [mode] parameter must not be null.
  ///
  /// The [positions] list is interpreted as a list of repeated pairs of x,y
  /// coordinates. It must not be null.
  ///
  /// The [textureCoordinates] list is interpreted as a list of repeated pairs
  /// of x,y coordinates, and must be the same length of [positions] if it
  /// is not null.
  ///
  /// The [colors] list is interpreted as a list of RGBA encoded colors, similar
  /// to [Color.value]. It must be half length of [positions] if it is not
  /// null.
  ///
  /// If the [indices] list is provided, all values in the list must be
  /// valid index values for [positions].
3599
  Vertices.raw(
3600 3601 3602 3603 3604 3605 3606
    VertexMode mode,
    Float32List positions, {
    Float32List? textureCoordinates,
    Int32List? colors,
    Uint16List? indices,
  }) : assert(mode != null), // ignore: unnecessary_null_comparison
       assert(positions != null) { // ignore: unnecessary_null_comparison
3607
    if (textureCoordinates != null && textureCoordinates.length != positions.length)
D
Dan Field 已提交
3608
      throw ArgumentError('"positions" and "textureCoordinates" lengths must match.');
3609
    if (colors != null && colors.length * 2 != positions.length)
D
Dan Field 已提交
3610
      throw ArgumentError('"positions" and "colors" lengths must match.');
3611
    if (indices != null && indices.any((int i) => i < 0 || i >= positions.length))
D
Dan Field 已提交
3612
      throw ArgumentError('"indices" values must be valid indices in the positions list.');
3613

3614
    if (!_init(this, mode.index, positions, textureCoordinates, colors, indices))
D
Dan Field 已提交
3615
      throw ArgumentError('Invalid configuration for vertices.');
3616 3617
  }

3618 3619
  bool _init(Vertices outVertices,
             int mode,
3620
             Float32List positions,
3621 3622 3623
             Float32List? textureCoordinates,
             Int32List? colors,
             Uint16List? indices) native 'Vertices_init';
3624 3625
}

A
Adam Barth 已提交
3626 3627
/// Defines how a list of points is interpreted when drawing a set of points.
///
3628
// ignore: deprecated_member_use
A
Adam Barth 已提交
3629
/// Used by [Canvas.drawPoints].
3630
// These enum values must be kept in sync with SkCanvas::PointMode.
A
Adam Barth 已提交
3631
enum PointMode {
3632 3633
  /// Draw each point separately.
  ///
I
Ian Hickson 已提交
3634
  /// If the [Paint.strokeCap] is [StrokeCap.round], then each point is drawn
3635 3636 3637 3638 3639 3640
  /// as a circle with the diameter of the [Paint.strokeWidth], filled as
  /// described by the [Paint] (ignoring [Paint.style]).
  ///
  /// Otherwise, each point is drawn as an axis-aligned square with sides of
  /// length [Paint.strokeWidth], filled as described by the [Paint] (ignoring
  /// [Paint.style]).
A
Adam Barth 已提交
3641 3642
  points,

3643 3644 3645 3646 3647 3648
  /// Draw each sequence of two points as a line segment.
  ///
  /// If the number of points is odd, then the last point is ignored.
  ///
  /// The lines are stroked as described by the [Paint] (ignoring
  /// [Paint.style]).
A
Adam Barth 已提交
3649 3650
  lines,

3651 3652 3653 3654
  /// Draw the entire sequence of point as one line.
  ///
  /// The lines are stroked as described by the [Paint] (ignoring
  /// [Paint.style]).
A
Adam Barth 已提交
3655 3656 3657
  polygon,
}

3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
/// Defines how a new clip region should be merged with the existing clip
/// region.
///
/// Used by [Canvas.clipRect].
enum ClipOp {
  /// Subtract the new region from the existing region.
  difference,

  /// Intersect the new region from the existing region.
  intersect,
}

A
Adam Barth 已提交
3670 3671
/// An interface for recording graphical operations.
///
H
Hixie 已提交
3672 3673 3674
/// [Canvas] objects are used in creating [Picture] objects, which can
/// themselves be used with a [SceneBuilder] to build a [Scene]. In
/// normal usage, however, this is all handled by the framework.
3675 3676 3677 3678
///
/// A canvas has a current transformation matrix which is applied to all
/// operations. Initially, the transformation matrix is the identity transform.
/// It can be modified using the [translate], [scale], [rotate], [skew],
3679
/// and [transform] methods.
3680 3681 3682 3683 3684 3685 3686
///
/// A canvas also has a current clip region which is applied to all operations.
/// Initially, the clip region is infinite. It can be modified using the
/// [clipRect], [clipRRect], and [clipPath] methods.
///
/// The current transform and clip can be saved and restored using the stack
/// managed by the [save], [saveLayer], and [restore] methods.
3687
class Canvas extends NativeFieldWrapperClass2 {
H
Hixie 已提交
3688 3689
  /// Creates a canvas for recording graphical operations into the
  /// given picture recorder.
A
Adam Barth 已提交
3690 3691
  ///
  /// Graphical operations that affect pixels entirely outside the given
3692
  /// `cullRect` might be discarded by the implementation. However, the
A
Adam Barth 已提交
3693
  /// implementation might draw outside these bounds if, for example, a command
3694
  /// draws partially inside and outside the `cullRect`. To ensure that pixels
3695 3696
  /// outside a given region are discarded, consider using a [clipRect]. The
  /// `cullRect` is optional; by default, all operations are kept.
H
Hixie 已提交
3697 3698 3699
  ///
  /// To end the recording, call [PictureRecorder.endRecording] on the
  /// given recorder.
3700
  @pragma('vm:entry-point')
3701
  Canvas(PictureRecorder recorder, [ Rect? cullRect ]) : assert(recorder != null) { // ignore: unnecessary_null_comparison
3702
    if (recorder.isRecording)
D
Dan Field 已提交
3703
      throw ArgumentError('"recorder" must not already be associated with another Canvas.');
3704 3705
    _recorder = recorder;
    _recorder!._canvas = this;
3706
    cullRect ??= Rect.largest;
3707
    _constructor(recorder, cullRect.left, cullRect.top, cullRect.right, cullRect.bottom);
3708
  }
3709 3710 3711 3712
  void _constructor(PictureRecorder recorder,
                    double left,
                    double top,
                    double right,
3713
                    double bottom) native 'Canvas_constructor';
3714

3715 3716 3717 3718 3719
  // The underlying Skia SkCanvas is owned by the PictureRecorder used to create this Canvas.
  // The Canvas holds a reference to the PictureRecorder to prevent the recorder from being
  // garbage collected until PictureRecorder.endRecording is called.
  PictureRecorder? _recorder;

H
Hixie 已提交
3720 3721 3722
  /// Saves a copy of the current transform and clip on the save stack.
  ///
  /// Call [restore] to pop the save stack.
3723 3724 3725 3726 3727
  ///
  /// See also:
  ///
  ///  * [saveLayer], which does the same thing but additionally also groups the
  ///    commands done until the matching [restore].
3728
  void save() native 'Canvas_save';
3729

3730 3731 3732
  /// Saves a copy of the current transform and clip on the save stack, and then
  /// creates a new group which subsequent calls will become a part of. When the
  /// save stack is later popped, the group will be flattened into a layer and
3733
  /// have the given `paint`'s [Paint.colorFilter] and [Paint.blendMode]
3734
  /// applied.
H
Hixie 已提交
3735
  ///
3736 3737 3738 3739 3740 3741
  /// This lets you create composite effects, for example making a group of
  /// drawing commands semi-transparent. Without using [saveLayer], each part of
  /// the group would be painted individually, so where they overlap would be
  /// darker than where they do not. By using [saveLayer] to group them
  /// together, they can be drawn with an opaque color at first, and then the
  /// entire group can be made transparent using the [saveLayer]'s paint.
H
Hixie 已提交
3742
  ///
3743
  /// Call [restore] to pop the save stack and apply the paint to the group.
3744 3745 3746
  ///
  /// ## Using saveLayer with clips
  ///
G
Greg Spencer 已提交
3747
  /// When a rectangular clip operation (from [clipRect]) is not axis-aligned
3748 3749
  /// with the raster buffer, or when the clip operation is not rectilinear
  /// (e.g. because it is a rounded rectangle clip created by [clipRRect] or an
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769
  /// arbitrarily complicated path clip created by [clipPath]), the edge of the
  /// clip needs to be anti-aliased.
  ///
  /// If two draw calls overlap at the edge of such a clipped region, without
  /// using [saveLayer], the first drawing will be anti-aliased with the
  /// background first, and then the second will be anti-aliased with the result
  /// of blending the first drawing and the background. On the other hand, if
  /// [saveLayer] is used immediately after establishing the clip, the second
  /// drawing will cover the first in the layer, and thus the second alone will
  /// be anti-aliased with the background when the layer is clipped and
  /// composited (when [restore] is called).
  ///
  /// For example, this [CustomPainter.paint] method paints a clean white
  /// rounded rectangle:
  ///
  /// ```dart
  /// void paint(Canvas canvas, Size size) {
  ///   Rect rect = Offset.zero & size;
  ///   canvas.save();
  ///   canvas.clipRRect(new RRect.fromRectXY(rect, 100.0, 100.0));
D
Dan Field 已提交
3770
  ///   canvas.saveLayer(rect, Paint());
3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836
  ///   canvas.drawPaint(new Paint()..color = Colors.red);
  ///   canvas.drawPaint(new Paint()..color = Colors.white);
  ///   canvas.restore();
  ///   canvas.restore();
  /// }
  /// ```
  ///
  /// On the other hand, this one renders a red outline, the result of the red
  /// paint being anti-aliased with the background at the clip edge, then the
  /// white paint being similarly anti-aliased with the background _including
  /// the clipped red paint_:
  ///
  /// ```dart
  /// void paint(Canvas canvas, Size size) {
  ///   // (this example renders poorly, prefer the example above)
  ///   Rect rect = Offset.zero & size;
  ///   canvas.save();
  ///   canvas.clipRRect(new RRect.fromRectXY(rect, 100.0, 100.0));
  ///   canvas.drawPaint(new Paint()..color = Colors.red);
  ///   canvas.drawPaint(new Paint()..color = Colors.white);
  ///   canvas.restore();
  /// }
  /// ```
  ///
  /// This point is moot if the clip only clips one draw operation. For example,
  /// the following paint method paints a pair of clean white rounded
  /// rectangles, even though the clips are not done on a separate layer:
  ///
  /// ```dart
  /// void paint(Canvas canvas, Size size) {
  ///   canvas.save();
  ///   canvas.clipRRect(new RRect.fromRectXY(Offset.zero & (size / 2.0), 50.0, 50.0));
  ///   canvas.drawPaint(new Paint()..color = Colors.white);
  ///   canvas.restore();
  ///   canvas.save();
  ///   canvas.clipRRect(new RRect.fromRectXY(size.center(Offset.zero) & (size / 2.0), 50.0, 50.0));
  ///   canvas.drawPaint(new Paint()..color = Colors.white);
  ///   canvas.restore();
  /// }
  /// ```
  ///
  /// (Incidentally, rather than using [clipRRect] and [drawPaint] to draw
  /// rounded rectangles like this, prefer the [drawRRect] method. These
  /// examples are using [drawPaint] as a proxy for "complicated draw operations
  /// that will get clipped", to illustrate the point.)
  ///
  /// ## Performance considerations
  ///
  /// Generally speaking, [saveLayer] is relatively expensive.
  ///
  /// There are a several different hardware architectures for GPUs (graphics
  /// processing units, the hardware that handles graphics), but most of them
  /// involve batching commands and reordering them for performance. When layers
  /// are used, they cause the rendering pipeline to have to switch render
  /// target (from one layer to another). Render target switches can flush the
  /// GPU's command buffer, which typically means that optimizations that one
  /// could get with larger batching are lost. Render target switches also
  /// generate a lot of memory churn because the GPU needs to copy out the
  /// current frame buffer contents from the part of memory that's optimized for
  /// writing, and then needs to copy it back in once the previous render target
  /// (layer) is restored.
  ///
  /// See also:
  ///
  ///  * [save], which saves the current state, but does not create a new layer
  ///    for subsequent commands.
3837 3838
  ///  * [BlendMode], which discusses the use of [Paint.blendMode] with
  ///    [saveLayer].
3839 3840
  void saveLayer(Rect? bounds, Paint paint) {
    assert(paint != null); // ignore: unnecessary_null_comparison
3841 3842 3843
    if (bounds == null) {
      _saveLayerWithoutBounds(paint._objects, paint._data);
    } else {
3844
      assert(_rectIsValid(bounds));
3845 3846 3847
      _saveLayer(bounds.left, bounds.top, bounds.right, bounds.bottom,
                 paint._objects, paint._data);
    }
3848
  }
3849
  void _saveLayerWithoutBounds(List<dynamic>? paintObjects, ByteData paintData)
3850
      native 'Canvas_saveLayerWithoutBounds';
3851 3852 3853 3854
  void _saveLayer(double left,
                  double top,
                  double right,
                  double bottom,
3855
                  List<dynamic>? paintObjects,
3856
                  ByteData paintData) native 'Canvas_saveLayer';
H
Hixie 已提交
3857 3858 3859 3860 3861

  /// Pops the current save stack, if there is anything to pop.
  /// Otherwise, does nothing.
  ///
  /// Use [save] and [saveLayer] to push state onto the stack.
3862 3863 3864
  ///
  /// If the state was pushed with with [saveLayer], then this call will also
  /// cause the new layer to be composited into the previous layer.
3865
  void restore() native 'Canvas_restore';
3866

H
Hixie 已提交
3867 3868 3869 3870 3871 3872
  /// Returns the number of items on the save stack, including the
  /// initial state. This means it returns 1 for a clean canvas, and
  /// that each call to [save] and [saveLayer] increments it, and that
  /// each matching call to [restore] decrements it.
  ///
  /// This number cannot go below 1.
3873
  int getSaveCount() native 'Canvas_getSaveCount';
3874

3875 3876
  /// Add a translation to the current transform, shifting the coordinate space
  /// horizontally by the first argument and vertically by the second argument.
3877
  void translate(double dx, double dy) native 'Canvas_translate';
3878 3879 3880 3881

  /// Add an axis-aligned scale to the current transform, scaling by the first
  /// argument in the horizontal direction and the second in the vertical
  /// direction.
3882 3883 3884
  ///
  /// If [sy] is unspecified, [sx] will be used for the scale in both
  /// directions.
3885
  void scale(double sx, [double? sy]) => _scale(sx, sy ?? sx);
3886 3887

  void _scale(double sx, double sy) native 'Canvas_scale';
3888 3889

  /// Add a rotation to the current transform. The argument is in radians clockwise.
3890
  void rotate(double radians) native 'Canvas_rotate';
3891 3892

  /// Add an axis-aligned skew to the current transform, with the first argument
D
Dan Field 已提交
3893 3894 3895
  /// being the horizontal skew in rise over run units clockwise around the
  /// origin, and the second argument being the vertical skew in rise over run
  /// units clockwise around the origin.
3896
  void skew(double sx, double sy) native 'Canvas_skew';
A
Adam Barth 已提交
3897

3898 3899
  /// Multiply the current transform by the specified 4⨉4 transformation matrix
  /// specified as a list of values in column-major order.
3900 3901
  void transform(Float64List matrix4) {
    assert(matrix4 != null); // ignore: unnecessary_null_comparison
A
Adam Barth 已提交
3902
    if (matrix4.length != 16)
D
Dan Field 已提交
3903
      throw ArgumentError('"matrix4" must have 16 entries.');
A
Adam Barth 已提交
3904 3905
    _transform(matrix4);
  }
3906
  void _transform(Float64List matrix4) native 'Canvas_transform';
A
Adam Barth 已提交
3907

3908 3909
  /// Reduces the clip region to the intersection of the current clip and the
  /// given rectangle.
3910
  ///
3911 3912 3913
  /// If [doAntiAlias] is true, then the clip will be anti-aliased.
  ///
  /// If multiple draw commands intersect with the clip boundary, this can result
3914 3915
  /// in incorrect blending at the clip boundary. See [saveLayer] for a
  /// discussion of how to address that.
3916 3917 3918
  ///
  /// Use [ClipOp.difference] to subtract the provided rectangle from the
  /// current clip.
3919
  void clipRect(Rect rect, { ClipOp clipOp = ClipOp.intersect, bool doAntiAlias = true }) {
3920
    assert(_rectIsValid(rect));
3921 3922
    assert(clipOp != null); // ignore: unnecessary_null_comparison
    assert(doAntiAlias != null); // ignore: unnecessary_null_comparison
3923
    _clipRect(rect.left, rect.top, rect.right, rect.bottom, clipOp.index, doAntiAlias);
3924 3925 3926 3927
  }
  void _clipRect(double left,
                 double top,
                 double right,
3928
                 double bottom,
3929 3930
                 int clipOp,
                 bool doAntiAlias) native 'Canvas_clipRect';
3931

3932 3933
  /// Reduces the clip region to the intersection of the current clip and the
  /// given rounded rectangle.
3934
  ///
3935 3936 3937
  /// If [doAntiAlias] is true, then the clip will be anti-aliased.
  ///
  /// If multiple draw commands intersect with the clip boundary, this can result
3938 3939
  /// in incorrect blending at the clip boundary. See [saveLayer] for a
  /// discussion of how to address that and some examples of using [clipRRect].
3940
  void clipRRect(RRect rrect, {bool doAntiAlias = true}) {
3941
    assert(_rrectIsValid(rrect));
3942
    assert(doAntiAlias != null); // ignore: unnecessary_null_comparison
D
Dan Field 已提交
3943
    _clipRRect(rrect._value32, doAntiAlias);
3944
  }
3945
  void _clipRRect(Float32List rrect, bool doAntiAlias) native 'Canvas_clipRRect';
3946

3947 3948
  /// Reduces the clip region to the intersection of the current clip and the
  /// given [Path].
3949
  ///
3950 3951 3952
  /// If [doAntiAlias] is true, then the clip will be anti-aliased.
  ///
  /// If multiple draw commands intersect with the clip boundary, this can result
3953 3954 3955
  /// multiple draw commands intersect with the clip boundary, this can result
  /// in incorrect blending at the clip boundary. See [saveLayer] for a
  /// discussion of how to address that.
3956 3957
  void clipPath(Path path, {bool doAntiAlias = true}) {
    // ignore: unnecessary_null_comparison
3958
    assert(path != null); // path is checked on the engine side
3959
    assert(doAntiAlias != null); // ignore: unnecessary_null_comparison
3960
    _clipPath(path, doAntiAlias);
3961
  }
3962
  void _clipPath(Path path, bool doAntiAlias) native 'Canvas_clipPath';
3963

3964
  /// Paints the given [Color] onto the canvas, applying the given
3965
  /// [BlendMode], with the given color being the source and the background
3966
  /// being the destination.
3967 3968 3969
  void drawColor(Color color, BlendMode blendMode) {
    assert(color != null); // ignore: unnecessary_null_comparison
    assert(blendMode != null); // ignore: unnecessary_null_comparison
3970
    _drawColor(color.value, blendMode.index);
3971
  }
3972
  void _drawColor(int color, int blendMode) native 'Canvas_drawColor';
3973

I
Ian Hickson 已提交
3974
  /// Draws a line between the given points using the given paint. The line is
3975
  /// stroked, the value of the [Paint.style] is ignored for this call.
I
Ian Hickson 已提交
3976 3977
  ///
  /// The `p1` and `p2` arguments are interpreted as offsets from the origin.
3978
  void drawLine(Offset p1, Offset p2, Paint paint) {
3979 3980
    assert(_offsetIsValid(p1));
    assert(_offsetIsValid(p2));
3981
    assert(paint != null); // ignore: unnecessary_null_comparison
I
Ian Hickson 已提交
3982
    _drawLine(p1.dx, p1.dy, p2.dx, p2.dy, paint._objects, paint._data);
3983
  }
3984 3985 3986 3987
  void _drawLine(double x1,
                 double y1,
                 double x2,
                 double y2,
3988
                 List<dynamic>? paintObjects,
3989
                 ByteData paintData) native 'Canvas_drawLine';
3990

3991 3992
  /// Fills the canvas with the given [Paint].
  ///
3993
  /// To fill the canvas with a solid color and blend mode, consider
3994
  /// [drawColor] instead.
3995 3996
  void drawPaint(Paint paint) {
    assert(paint != null); // ignore: unnecessary_null_comparison
3997 3998
    _drawPaint(paint._objects, paint._data);
  }
3999
  void _drawPaint(List<dynamic>? paintObjects, ByteData paintData) native 'Canvas_drawPaint';
4000

4001 4002
  /// Draws a rectangle with the given [Paint]. Whether the rectangle is filled
  /// or stroked (or both) is controlled by [Paint.style].
4003
  void drawRect(Rect rect, Paint paint) {
4004
    assert(_rectIsValid(rect));
4005
    assert(paint != null); // ignore: unnecessary_null_comparison
4006 4007
    _drawRect(rect.left, rect.top, rect.right, rect.bottom,
              paint._objects, paint._data);
4008 4009 4010 4011 4012
  }
  void _drawRect(double left,
                 double top,
                 double right,
                 double bottom,
4013
                 List<dynamic>? paintObjects,
4014
                 ByteData paintData) native 'Canvas_drawRect';
4015

4016 4017
  /// Draws a rounded rectangle with the given [Paint]. Whether the rectangle is
  /// filled or stroked (or both) is controlled by [Paint.style].
4018
  void drawRRect(RRect rrect, Paint paint) {
4019
    assert(_rrectIsValid(rrect));
4020
    assert(paint != null); // ignore: unnecessary_null_comparison
D
Dan Field 已提交
4021
    _drawRRect(rrect._value32, paint._objects, paint._data);
4022 4023
  }
  void _drawRRect(Float32List rrect,
4024
                  List<dynamic>? paintObjects,
4025
                  ByteData paintData) native 'Canvas_drawRRect';
4026

4027 4028 4029 4030 4031
  /// Draws a shape consisting of the difference between two rounded rectangles
  /// with the given [Paint]. Whether this shape is filled or stroked (or both)
  /// is controlled by [Paint.style].
  ///
  /// This shape is almost but not quite entirely unlike an annulus.
4032
  void drawDRRect(RRect outer, RRect inner, Paint paint) {
4033 4034
    assert(_rrectIsValid(outer));
    assert(_rrectIsValid(inner));
4035
    assert(paint != null); // ignore: unnecessary_null_comparison
D
Dan Field 已提交
4036
    _drawDRRect(outer._value32, inner._value32, paint._objects, paint._data);
4037 4038 4039
  }
  void _drawDRRect(Float32List outer,
                   Float32List inner,
4040
                   List<dynamic>? paintObjects,
4041
                   ByteData paintData) native 'Canvas_drawDRRect';
4042

4043 4044 4045
  /// Draws an axis-aligned oval that fills the given axis-aligned rectangle
  /// with the given [Paint]. Whether the oval is filled or stroked (or both) is
  /// controlled by [Paint.style].
4046
  void drawOval(Rect rect, Paint paint) {
4047
    assert(_rectIsValid(rect));
4048
    assert(paint != null); // ignore: unnecessary_null_comparison
4049 4050
    _drawOval(rect.left, rect.top, rect.right, rect.bottom,
              paint._objects, paint._data);
4051 4052 4053 4054 4055
  }
  void _drawOval(double left,
                 double top,
                 double right,
                 double bottom,
4056
                 List<dynamic>? paintObjects,
4057
                 ByteData paintData) native 'Canvas_drawOval';
4058

I
Ian Hickson 已提交
4059 4060 4061
  /// Draws a circle centered at the point given by the first argument and
  /// that has the radius given by the second argument, with the [Paint] given in
  /// the third argument. Whether the circle is filled or stroked (or both) is
4062
  /// controlled by [Paint.style].
4063
  void drawCircle(Offset c, double radius, Paint paint) {
4064
    assert(_offsetIsValid(c));
4065
    assert(paint != null); // ignore: unnecessary_null_comparison
I
Ian Hickson 已提交
4066
    _drawCircle(c.dx, c.dy, radius, paint._objects, paint._data);
4067
  }
4068 4069 4070
  void _drawCircle(double x,
                   double y,
                   double radius,
4071
                   List<dynamic>? paintObjects,
4072
                   ByteData paintData) native 'Canvas_drawCircle';
4073

4074 4075 4076 4077 4078 4079 4080
  /// Draw an arc scaled to fit inside the given rectangle.
  ///
  /// It starts from `startAngle` radians around the oval up to
  /// `startAngle` + `sweepAngle` radians around the oval, with zero radians
  /// being the point on the right hand side of the oval that crosses the
  /// horizontal line that intersects the center of the rectangle and with positive
  /// angles going clockwise around the oval. If `useCenter` is true, the arc is
4081 4082 4083 4084
  /// closed back to the center, forming a circle sector. Otherwise, the arc is
  /// not closed, forming a circle segment.
  ///
  /// This method is optimized for drawing arcs and should be faster than [Path.arcTo].
4085
  void drawArc(Rect rect, double startAngle, double sweepAngle, bool useCenter, Paint paint) {
4086
    assert(_rectIsValid(rect));
4087
    assert(paint != null); // ignore: unnecessary_null_comparison
4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
    _drawArc(rect.left, rect.top, rect.right, rect.bottom, startAngle,
             sweepAngle, useCenter, paint._objects, paint._data);
  }
  void _drawArc(double left,
                double top,
                double right,
                double bottom,
                double startAngle,
                double sweepAngle,
                bool useCenter,
4098
                List<dynamic>? paintObjects,
4099
                ByteData paintData) native 'Canvas_drawArc';
4100

4101 4102 4103 4104 4105
  /// Draws the given [Path] with the given [Paint].
  ///
  /// Whether this shape is filled or stroked (or both) is controlled by
  /// [Paint.style]. If the path is filled, then sub-paths within it are
  /// implicitly closed (see [Path.close]).
4106 4107
  void drawPath(Path path, Paint paint) {
    // ignore: unnecessary_null_comparison
4108
    assert(path != null); // path is checked on the engine side
4109
    assert(paint != null); // ignore: unnecessary_null_comparison
4110 4111 4112
    _drawPath(path, paint._objects, paint._data);
  }
  void _drawPath(Path path,
4113
                 List<dynamic>? paintObjects,
4114
                 ByteData paintData) native 'Canvas_drawPath';
4115

4116
  /// Draws the given [Image] into the canvas with its top-left corner at the
I
Ian Hickson 已提交
4117
  /// given [Offset]. The image is composited into the canvas using the given [Paint].
4118 4119
  void drawImage(Image image, Offset offset, Paint paint) {
    // ignore: unnecessary_null_comparison
4120
    assert(image != null); // image is checked on the engine side
4121
    assert(_offsetIsValid(offset));
4122
    assert(paint != null); // ignore: unnecessary_null_comparison
4123
    _drawImage(image._image, offset.dx, offset.dy, paint._objects, paint._data);
4124
  }
4125
  void _drawImage(_Image image,
4126 4127
                  double x,
                  double y,
4128
                  List<dynamic>? paintObjects,
4129
                  ByteData paintData) native 'Canvas_drawImage';
4130

4131 4132
  /// Draws the subset of the given image described by the `src` argument into
  /// the canvas in the axis-aligned rectangle given by the `dst` argument.
4133
  ///
4134 4135
  /// This might sample from outside the `src` rect by up to half the width of
  /// an applied filter.
4136 4137 4138 4139
  ///
  /// Multiple calls to this method with different arguments (from the same
  /// image) can be batched into a single call to [drawAtlas] to improve
  /// performance.
4140 4141
  void drawImageRect(Image image, Rect src, Rect dst, Paint paint) {
    // ignore: unnecessary_null_comparison
4142
    assert(image != null); // image is checked on the engine side
4143 4144
    assert(_rectIsValid(src));
    assert(_rectIsValid(dst));
4145
    assert(paint != null); // ignore: unnecessary_null_comparison
4146
    _drawImageRect(image._image,
4147 4148 4149 4150 4151 4152 4153 4154
                   src.left,
                   src.top,
                   src.right,
                   src.bottom,
                   dst.left,
                   dst.top,
                   dst.right,
                   dst.bottom,
4155 4156
                   paint._objects,
                   paint._data);
4157
  }
4158
  void _drawImageRect(_Image image,
4159 4160 4161 4162 4163 4164 4165 4166
                      double srcLeft,
                      double srcTop,
                      double srcRight,
                      double srcBottom,
                      double dstLeft,
                      double dstTop,
                      double dstRight,
                      double dstBottom,
4167
                      List<dynamic>? paintObjects,
4168
                      ByteData paintData) native 'Canvas_drawImageRect';
4169

4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182
  /// Draws the given [Image] into the canvas using the given [Paint].
  ///
  /// The image is drawn in nine portions described by splitting the image by
  /// drawing two horizontal lines and two vertical lines, where the `center`
  /// argument 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 the `center` argument.)
  ///
  /// The four regions in the corners are drawn, without scaling, in the four
  /// corners of the destination rectangle described by `dst`. The remaining
  /// five regions are drawn by stretching them to fit such that they exactly
  /// cover the destination rectangle while maintaining their relative
  /// positions.
4183 4184
  void drawImageNine(Image image, Rect center, Rect dst, Paint paint) {
    // ignore: unnecessary_null_comparison
4185
    assert(image != null); // image is checked on the engine side
4186 4187
    assert(_rectIsValid(center));
    assert(_rectIsValid(dst));
4188
    assert(paint != null); // ignore: unnecessary_null_comparison
4189
    _drawImageNine(image._image,
4190 4191 4192 4193 4194 4195 4196 4197
                   center.left,
                   center.top,
                   center.right,
                   center.bottom,
                   dst.left,
                   dst.top,
                   dst.right,
                   dst.bottom,
4198 4199
                   paint._objects,
                   paint._data);
4200
  }
4201
  void _drawImageNine(_Image image,
4202 4203 4204 4205 4206 4207 4208 4209
                      double centerLeft,
                      double centerTop,
                      double centerRight,
                      double centerBottom,
                      double dstLeft,
                      double dstTop,
                      double dstRight,
                      double dstBottom,
4210
                      List<dynamic>? paintObjects,
4211
                      ByteData paintData) native 'Canvas_drawImageNine';
4212

H
Hixie 已提交
4213 4214
  /// Draw the given picture onto the canvas. To create a picture, see
  /// [PictureRecorder].
4215 4216
  void drawPicture(Picture picture) {
    // ignore: unnecessary_null_comparison
4217 4218 4219
    assert(picture != null); // picture is checked on the engine side
    _drawPicture(picture);
  }
4220
  void _drawPicture(Picture picture) native 'Canvas_drawPicture';
4221

I
Ian Hickson 已提交
4222 4223
  /// Draws the text in the given [Paragraph] into this canvas at the given
  /// [Offset].
A
Adam Barth 已提交
4224
  ///
I
Ian Hickson 已提交
4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241
  /// The [Paragraph] object must have had [Paragraph.layout] called on it
  /// first.
  ///
  /// To align the text, set the `textAlign` on the [ParagraphStyle] object
  /// passed to the [new ParagraphBuilder] constructor. For more details see
  /// [TextAlign] and the discussion at [new ParagraphStyle].
  ///
  /// If the text is left aligned or justified, the left margin will be at the
  /// position specified by the `offset` argument's [Offset.dx] coordinate.
  ///
  /// If the text is right aligned or justified, the right margin will be at the
  /// position described by adding the [ParagraphConstraints.width] given to
  /// [Paragraph.layout], to the `offset` argument's [Offset.dx] coordinate.
  ///
  /// If the text is centered, the centering axis will be at the position
  /// described by adding half of the [ParagraphConstraints.width] given to
  /// [Paragraph.layout], to the `offset` argument's [Offset.dx] coordinate.
4242 4243
  void drawParagraph(Paragraph paragraph, Offset offset) {
    assert(paragraph != null); // ignore: unnecessary_null_comparison
4244
    assert(_offsetIsValid(offset));
4245
    paragraph._paint(this, offset.dx, offset.dy);
4246
  }
A
Adam Barth 已提交
4247

A
Adam Barth 已提交
4248
  /// Draws a sequence of points according to the given [PointMode].
I
Ian Hickson 已提交
4249 4250
  ///
  /// The `points` argument is interpreted as offsets from the origin.
4251 4252 4253 4254 4255
  ///
  /// See also:
  ///
  ///  * [drawRawPoints], which takes `points` as a [Float32List] rather than a
  ///    [List<Offset>].
4256 4257 4258 4259
  void drawPoints(PointMode pointMode, List<Offset> points, Paint paint) {
    assert(pointMode != null); // ignore: unnecessary_null_comparison
    assert(points != null); // ignore: unnecessary_null_comparison
    assert(paint != null); // ignore: unnecessary_null_comparison
4260
    _drawPoints(paint._objects, paint._data, pointMode.index, _encodePointList(points));
A
Adam Barth 已提交
4261
  }
4262 4263 4264 4265 4266 4267 4268 4269 4270 4271

  /// Draws a sequence of points according to the given [PointMode].
  ///
  /// The `points` argument is interpreted as a list of pairs of floating point
  /// numbers, where each pair represents an x and y offset from the origin.
  ///
  /// See also:
  ///
  ///  * [drawPoints], which takes `points` as a [List<Offset>] rather than a
  ///    [List<Float32List>].
4272 4273 4274 4275
  void drawRawPoints(PointMode pointMode, Float32List points, Paint paint) {
    assert(pointMode != null); // ignore: unnecessary_null_comparison
    assert(points != null); // ignore: unnecessary_null_comparison
    assert(paint != null); // ignore: unnecessary_null_comparison
4276
    if (points.length % 2 != 0)
D
Dan Field 已提交
4277
      throw ArgumentError('"points" must have an even number of values.');
4278 4279 4280
    _drawPoints(paint._objects, paint._data, pointMode.index, points);
  }

4281
  void _drawPoints(List<dynamic>? paintObjects,
4282 4283
                   ByteData paintData,
                   int pointMode,
4284
                   Float32List points) native 'Canvas_drawPoints';
A
Adam Barth 已提交
4285

4286 4287 4288 4289 4290 4291 4292 4293
  /// Draws the set of [Vertices] onto the canvas.
  ///
  /// All parameters must not be null.
  ///
  /// See also:
  ///   * [new Vertices], which creates a set of vertices to draw on the canvas.
  ///   * [Vertices.raw], which creates the vertices using typed data lists
  ///     rather than unencoded lists.
4294 4295
  void drawVertices(Vertices vertices, BlendMode blendMode, Paint paint) {
    // ignore: unnecessary_null_comparison
4296
    assert(vertices != null); // vertices is checked on the engine side
4297 4298
    assert(paint != null); // ignore: unnecessary_null_comparison
    assert(blendMode != null); // ignore: unnecessary_null_comparison
4299
    _drawVertices(vertices, blendMode.index, paint._objects, paint._data);
4300
  }
4301
  void _drawVertices(Vertices vertices,
4302
                     int blendMode,
4303
                     List<dynamic>? paintObjects,
4304
                     ByteData paintData) native 'Canvas_drawVertices';
4305

4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342
  /// Draws many parts of an image - the [atlas] - onto the canvas.
  ///
  /// This method allows for optimization when you want to draw many parts of an
  /// image onto the canvas, such as when using sprites or zooming. It is more efficient
  /// than using multiple calls to [drawImageRect] and provides more functionality
  /// to individually transform each image part by a separate rotation or scale and
  /// blend or modulate those parts with a solid color.
  ///
  /// The method takes a list of [Rect] objects that each define a piece of the
  /// [atlas] image to be drawn independently. Each [Rect] is associated with an
  /// [RSTransform] entry in the [transforms] list which defines the location,
  /// rotation, and (uniform) scale with which to draw that portion of the image.
  /// Each [Rect] can also be associated with an optional [Color] which will be
  /// composed with the associated image part using the [blendMode] before blending
  /// the result onto the canvas. The full operation can be broken down as:
  ///
  /// - Blend each rectangular portion of the image specified by an entry in the
  /// [rects] argument with its associated entry in the [colors] list using the
  /// [blendMode] argument (if a color is specified). In this part of the operation,
  /// the image part will be considered the source of the operation and the associated
  /// color will be considered the destination.
  /// - Blend the result from the first step onto the canvas using the translation,
  /// rotation, and scale properties expressed in the associated entry in the
  /// [transforms] list using the properties of the [Paint] object.
  ///
  /// If the first stage of the operation which blends each part of the image with
  /// a color is needed, then both the [colors] and [blendMode] arguments must
  /// not be null and there must be an entry in the [colors] list for each
  /// image part. If that stage is not needed, then the [colors] argument can
  /// be either null or an empty list and the [blendMode] argument may also be null.
  ///
  /// The optional [cullRect] argument can provide an estimate of the bounds of the
  /// coordinates rendered by all components of the atlas to be compared against
  /// the clip to quickly reject the operation if it does not intersect.
  ///
  /// An example usage to render many sprites from a single sprite atlas with no
  /// rotations or scales:
4343
  ///
4344 4345 4346 4347 4348 4349
  /// ```dart
  /// class Sprite {
  ///   int index;
  ///   double centerX;
  ///   double centerY;
  /// }
4350
  ///
4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427
  /// class MyPainter extends CustomPainter {
  ///   // assume spriteAtlas contains N 10x10 sprites side by side in a (N*10)x10 image
  ///   ui.Image spriteAtlas;
  ///   List<Sprite> allSprites;
  ///
  ///   @override
  ///   void paint(Canvas canvas, Size size) {
  ///     Paint paint = Paint();
  ///     canvas.drawAtlas(spriteAtlas, <RSTransform>[
  ///       for (Sprite sprite in allSprites)
  ///         RSTransform.fromComponents(
  ///           rotation: 0.0,
  ///           scale: 1.0,
  ///           // Center of the sprite relative to its rect
  ///           anchorX: 5.0,
  ///           anchorY: 5.0,
  ///           // Location at which to draw the center of the sprite
  ///           translateX: sprite.centerX,
  ///           translateY: sprite.centerY,
  ///         ),
  ///     ], <Rect>[
  ///       for (Sprite sprite in allSprites)
  ///         Rect.fromLTWH(sprite.index * 10.0, 0.0, 10.0, 10.0),
  ///     ], null, null, null, paint);
  ///   }
  ///
  ///   ...
  /// }
  /// ```
  ///
  /// Another example usage which renders sprites with an optional opacity and rotation:
  ///
  /// ```dart
  /// class Sprite {
  ///   int index;
  ///   double centerX;
  ///   double centerY;
  ///   int alpha;
  ///   double rotation;
  /// }
  ///
  /// class MyPainter extends CustomPainter {
  ///   // assume spriteAtlas contains N 10x10 sprites side by side in a (N*10)x10 image
  ///   ui.Image spriteAtlas;
  ///   List<Sprite> allSprites;
  ///
  ///   @override
  ///   void paint(Canvas canvas, Size size) {
  ///     Paint paint = Paint();
  ///     canvas.drawAtlas(spriteAtlas, <RSTransform>[
  ///       for (Sprite sprite in allSprites)
  ///         RSTransform.fromComponents(
  ///           rotation: sprite.rotation,
  ///           scale: 1.0,
  ///           // Center of the sprite relative to its rect
  ///           anchorX: 5.0,
  ///           anchorY: 5.0,
  ///           // Location at which to draw the center of the sprite
  ///           translateX: sprite.centerX,
  ///           translateY: sprite.centerY,
  ///         ),
  ///     ], <Rect>[
  ///       for (Sprite sprite in allSprites)
  ///         Rect.fromLTWH(sprite.index * 10.0, 0.0, 10.0, 10.0),
  ///     ], <Color>[
  ///       for (Sprite sprite in allSprites)
  ///         Color.white.withAlpha(sprite.alpha),
  ///     ], BlendMode.srcIn, null, paint);
  ///   }
  ///
  ///   ...
  /// }
  /// ```
  ///
  /// The length of the [transforms] and [rects] lists must be equal and
  /// if the [colors] argument is not null then it must either be empty or
  /// have the same length as the other two lists.
4428 4429 4430 4431 4432
  ///
  /// See also:
  ///
  ///  * [drawRawAtlas], which takes its arguments as typed data lists rather
  ///    than objects.
4433 4434 4435
  void drawAtlas(Image atlas,
                 List<RSTransform> transforms,
                 List<Rect> rects,
4436 4437
                 List<Color>? colors,
                 BlendMode? blendMode,
4438 4439 4440
                 Rect? cullRect,
                 Paint paint) {
    // ignore: unnecessary_null_comparison
4441
    assert(atlas != null); // atlas is checked on the engine side
4442 4443
    assert(transforms != null); // ignore: unnecessary_null_comparison
    assert(rects != null); // ignore: unnecessary_null_comparison
4444
    assert(colors == null || colors.isEmpty || blendMode != null);
4445
    assert(paint != null); // ignore: unnecessary_null_comparison
4446

4447
    final int rectCount = rects.length;
4448
    if (transforms.length != rectCount)
D
Dan Field 已提交
4449
      throw ArgumentError('"transforms" and "rects" lengths must match.');
4450
    if (colors != null && colors.isNotEmpty && colors.length != rectCount)
D
Dan Field 已提交
4451
      throw ArgumentError('If non-null, "colors" length must match that of "transforms" and "rects".');
4452

D
Dan Field 已提交
4453 4454
    final Float32List rstTransformBuffer = Float32List(rectCount * 4);
    final Float32List rectBuffer = Float32List(rectCount * 4);
4455 4456 4457 4458 4459 4460 4461 4462

    for (int i = 0; i < rectCount; ++i) {
      final int index0 = i * 4;
      final int index1 = index0 + 1;
      final int index2 = index0 + 2;
      final int index3 = index0 + 3;
      final RSTransform rstTransform = transforms[i];
      final Rect rect = rects[i];
4463
      assert(_rectIsValid(rect));
4464 4465 4466 4467 4468 4469 4470 4471
      rstTransformBuffer[index0] = rstTransform.scos;
      rstTransformBuffer[index1] = rstTransform.ssin;
      rstTransformBuffer[index2] = rstTransform.tx;
      rstTransformBuffer[index3] = rstTransform.ty;
      rectBuffer[index0] = rect.left;
      rectBuffer[index1] = rect.top;
      rectBuffer[index2] = rect.right;
      rectBuffer[index3] = rect.bottom;
4472
    }
4473

4474
    final Int32List? colorBuffer = (colors == null || colors.isEmpty) ? null : _encodeColorList(colors);
4475
    final Float32List? cullRectBuffer = cullRect?._value32;
4476

4477
    _drawAtlas(
4478
      paint._objects, paint._data, atlas._image, rstTransformBuffer, rectBuffer,
4479
      colorBuffer, (blendMode ?? BlendMode.src).index, cullRectBuffer
4480
    );
4481
  }
4482

4483 4484 4485 4486 4487 4488 4489 4490 4491
  /// Draws many parts of an image - the [atlas] - onto the canvas.
  ///
  /// This method allows for optimization when you want to draw many parts of an
  /// image onto the canvas, such as when using sprites or zooming. It is more efficient
  /// than using multiple calls to [drawImageRect] and provides more functionality
  /// to individually transform each image part by a separate rotation or scale and
  /// blend or modulate those parts with a solid color. It is also more efficient
  /// than [drawAtlas] as the data in the arguments is already packed in a format
  /// that can be directly used by the rendering code.
4492
  ///
4493 4494
  /// A full description of how this method uses its arguments to draw onto the
  /// canvas can be found in the description of the [drawAtlas] method.
4495 4496 4497 4498 4499 4500 4501 4502 4503
  ///
  /// The [rstTransforms] argument is interpreted as a list of four-tuples, with
  /// each tuple being ([RSTransform.scos], [RSTransform.ssin],
  /// [RSTransform.tx], [RSTransform.ty]).
  ///
  /// The [rects] argument is interpreted as a list of four-tuples, with each
  /// tuple being ([Rect.left], [Rect.top], [Rect.right], [Rect.bottom]).
  ///
  /// The [colors] argument, which can be null, is interpreted as a list of
4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618
  /// 32-bit colors, with the same packing as [Color.value]. If the [colors]
  /// argument is not null then the [blendMode] argument must also not be null.
  ///
  /// An example usage to render many sprites from a single sprite atlas with no rotations
  /// or scales:
  ///
  /// ```dart
  /// class Sprite {
  ///   int index;
  ///   double centerX;
  ///   double centerY;
  /// }
  ///
  /// class MyPainter extends CustomPainter {
  ///   // assume spriteAtlas contains N 10x10 sprites side by side in a (N*10)x10 image
  ///   ui.Image spriteAtlas;
  ///   List<Sprite> allSprites;
  ///
  ///   @override
  ///   void paint(Canvas canvas, Size size) {
  ///     // For best advantage, these lists should be cached and only specific
  ///     // entries updated when the sprite information changes. This code is
  ///     // illustrative of how to set up the data and not a recommendation for
  ///     // optimal usage.
  ///     Float32List rectList = Float32List(allSprites.length * 4);
  ///     Float32List transformList = Float32List(allSprites.length * 4);
  ///     for (int i = 0; i < allSprites.length; i++) {
  ///       final double rectX = sprite.spriteIndex * 10.0;
  ///       rectList[i * 4 + 0] = rectX;
  ///       rectList[i * 4 + 1] = 0.0;
  ///       rectList[i * 4 + 2] = rectX + 10.0;
  ///       rectList[i * 4 + 3] = 10.0;
  ///
  ///       // This example sets the RSTransform values directly for a common case of no
  ///       // rotations or scales and just a translation to position the atlas entry. For
  ///       // more complicated transforms one could use the RSTransform class to compute
  ///       // the necessary values or do the same math directly.
  ///       transformList[i * 4 + 0] = 1.0;
  ///       transformList[i * 4 + 1] = 0.0;
  ///       transformList[i * 4 + 2] = sprite.centerX - 5.0;
  ///       transformList[i * 4 + 2] = sprite.centerY - 5.0;
  ///     }
  ///     Paint paint = Paint();
  ///     canvas.drawAtlas(spriteAtlas, transformList, rectList, null, null, null, paint);
  ///   }
  ///
  ///   ...
  /// }
  /// ```
  ///
  /// Another example usage which renders sprites with an optional opacity and rotation:
  ///
  /// ```dart
  /// class Sprite {
  ///   int index;
  ///   double centerX;
  ///   double centerY;
  ///   int alpha;
  ///   double rotation;
  /// }
  ///
  /// class MyPainter extends CustomPainter {
  ///   // assume spriteAtlas contains N 10x10 sprites side by side in a (N*10)x10 image
  ///   ui.Image spriteAtlas;
  ///   List<Sprite> allSprites;
  ///
  ///   @override
  ///   void paint(Canvas canvas, Size size) {
  ///     // For best advantage, these lists should be cached and only specific
  ///     // entries updated when the sprite information changes. This code is
  ///     // illustrative of how to set up the data and not a recommendation for
  ///     // optimal usage.
  ///     Float32List rectList = Float32List(allSprites.length * 4);
  ///     Float32List transformList = Float32List(allSprites.length * 4);
  ///     Int32List colorList = Int32List(allSprites.length);
  ///     for (int i = 0; i < allSprites.length; i++) {
  ///       final double rectX = sprite.spriteIndex * 10.0;
  ///       rectList[i * 4 + 0] = rectX;
  ///       rectList[i * 4 + 1] = 0.0;
  ///       rectList[i * 4 + 2] = rectX + 10.0;
  ///       rectList[i * 4 + 3] = 10.0;
  ///
  ///       // This example uses an RSTransform object to compute the necessary values for
  ///       // the transform using a factory helper method because the sprites contain
  ///       // rotation values which are not trivial to work with. But if the math for the
  ///       // values falls out from other calculations on the sprites then the values could
  ///       // possibly be generated directly from the sprite update code.
  ///       final RSTransform transform = RSTransform.fromComponents(
  ///         rotation: sprite.rotation,
  ///         scale: 1.0,
  ///         // Center of the sprite relative to its rect
  ///         anchorX: 5.0,
  ///         anchorY: 5.0,
  ///         // Location at which to draw the center of the sprite
  ///         translateX: sprite.centerX,
  ///         translateY: sprite.centerY,
  ///       );
  ///       transformList[i * 4 + 0] = transform.scos;
  ///       transformList[i * 4 + 1] = transform.ssin;
  ///       transformList[i * 4 + 2] = transform.tx;
  ///       transformList[i * 4 + 2] = transform.ty;
  ///
  ///       // This example computes the color value directly, but one could also compute
  ///       // an actual Color object and use its Color.value getter for the same result.
  ///       // Since we are using BlendMode.srcIn, only the alpha component matters for
  ///       // these colors which makes this a simple shift operation.
  ///       colorList[i] = sprite.alpha << 24;
  ///     }
  ///     Paint paint = Paint();
  ///     canvas.drawAtlas(spriteAtlas, transformList, rectList, colorList, BlendMode.srcIn, null, paint);
  ///   }
  ///
  ///   ...
  /// }
  /// ```
4619 4620 4621 4622 4623
  ///
  /// See also:
  ///
  ///  * [drawAtlas], which takes its arguments as objects rather than typed
  ///    data lists.
4624 4625 4626
  void drawRawAtlas(Image atlas,
                    Float32List rstTransforms,
                    Float32List rects,
4627 4628
                    Int32List? colors,
                    BlendMode? blendMode,
4629 4630 4631
                    Rect? cullRect,
                    Paint paint) {
    // ignore: unnecessary_null_comparison
4632
    assert(atlas != null); // atlas is checked on the engine side
4633 4634
    assert(rstTransforms != null); // ignore: unnecessary_null_comparison
    assert(rects != null); // ignore: unnecessary_null_comparison
4635
    assert(colors == null || blendMode != null);
4636
    assert(paint != null); // ignore: unnecessary_null_comparison
4637

4638
    final int rectCount = rects.length;
4639
    if (rstTransforms.length != rectCount)
D
Dan Field 已提交
4640
      throw ArgumentError('"rstTransforms" and "rects" lengths must match.');
4641
    if (rectCount % 4 != 0)
D
Dan Field 已提交
4642
      throw ArgumentError('"rstTransforms" and "rects" lengths must be a multiple of four.');
4643
    if (colors != null && colors.length * 4 != rectCount)
D
Dan Field 已提交
4644
      throw ArgumentError('If non-null, "colors" length must be one fourth the length of "rstTransforms" and "rects".');
4645 4646

    _drawAtlas(
4647
      paint._objects, paint._data, atlas._image, rstTransforms, rects,
4648
      colors, (blendMode ?? BlendMode.src).index, cullRect?._value32
4649 4650 4651
    );
  }

4652
  void _drawAtlas(List<dynamic>? paintObjects,
4653
                  ByteData paintData,
4654
                  _Image atlas,
4655 4656
                  Float32List rstTransforms,
                  Float32List rects,
4657
                  Int32List? colors,
4658
                  int blendMode,
4659
                  Float32List? cullRect) native 'Canvas_drawAtlas';
4660 4661 4662

  /// Draws a shadow for a [Path] representing the given material elevation.
  ///
4663 4664 4665 4666
  /// The `transparentOccluder` argument should be true if the occluding object
  /// is not opaque.
  ///
  /// The arguments must not be null.
4667 4668
  void drawShadow(Path path, Color color, double elevation, bool transparentOccluder) {
    // ignore: unnecessary_null_comparison
4669
    assert(path != null); // path is checked on the engine side
4670 4671
    assert(color != null); // ignore: unnecessary_null_comparison
    assert(transparentOccluder != null); // ignore: unnecessary_null_comparison
4672 4673 4674 4675
    _drawShadow(path, color.value, elevation, transparentOccluder);
  }
  void _drawShadow(Path path,
                   int color,
4676
                   double elevation,
4677
                   bool transparentOccluder) native 'Canvas_drawShadow';
4678 4679
}

A
Adam Barth 已提交
4680
/// An object representing a sequence of recorded graphical operations.
4681 4682
///
/// To create a [Picture], use a [PictureRecorder].
H
Hixie 已提交
4683 4684 4685 4686
///
/// A [Picture] can be placed in a [Scene] using a [SceneBuilder], via
/// the [SceneBuilder.addPicture] method. A [Picture] can also be
/// drawn into a [Canvas], using the [Canvas.drawPicture] method.
S
sjindel-google 已提交
4687
@pragma('vm:entry-point')
4688 4689 4690
class Picture extends NativeFieldWrapperClass2 {
  /// This class is created by the engine, and should not be instantiated
  /// or extended directly.
4691
  ///
4692
  /// To create a [Picture], use a [PictureRecorder].
4693
  @pragma('vm:entry-point')
4694
  Picture._();
4695

A
Adam Barth 已提交
4696
  /// Creates an image from this picture.
4697
  ///
4698 4699 4700
  /// The returned image will be `width` pixels wide and `height` pixels high.
  /// The picture is rasterized within the 0 (left), 0 (top), `width` (right),
  /// `height` (bottom) bounds. Content outside these bounds is clipped.
4701
  ///
A
Adam Barth 已提交
4702 4703
  /// Although the image is returned synchronously, the picture is actually
  /// rasterized the first time the image is drawn and then cached.
4704
  Future<Image> toImage(int width, int height) {
4705
    if (width <= 0 || height <= 0)
D
Dan Field 已提交
4706
      throw Exception('Invalid image dimensions.');
4707
    return _futurize(
4708 4709 4710
      (_Callback<Image> callback) => _toImage(width, height, (_Image image) {
        callback(Image._(image));
      }),
4711 4712 4713
    );
  }

4714
  String? _toImage(int width, int height, _Callback<_Image> callback) native 'Picture_toImage';
A
Adam Barth 已提交
4715

I
Ian Hickson 已提交
4716 4717
  /// Release the resources used by this object. The object is no longer usable
  /// after this method is called.
4718
  void dispose() native 'Picture_dispose';
4719 4720

  /// Returns the approximate number of bytes allocated for this object.
4721
  ///
4722 4723
  /// The actual size of this picture may be larger, particularly if it contains
  /// references to image or other large objects.
4724
  int get approximateBytesUsed native 'Picture_GetAllocationSize';
4725 4726
}

A
Adam Barth 已提交
4727 4728 4729
/// Records a [Picture] containing a sequence of graphical operations.
///
/// To begin recording, construct a [Canvas] to record the commands.
4730
/// To end recording, use the [PictureRecorder.endRecording] method.
4731
class PictureRecorder extends NativeFieldWrapperClass2 {
4732 4733 4734
  /// Creates a new idle PictureRecorder. To associate it with a
  /// [Canvas] and begin recording, pass this [PictureRecorder] to the
  /// [Canvas] constructor.
4735
  @pragma('vm:entry-point')
4736
  PictureRecorder() { _constructor(); }
4737
  void _constructor() native 'PictureRecorder_constructor';
4738

A
Adam Barth 已提交
4739 4740
  /// Whether this object is currently recording commands.
  ///
4741 4742 4743 4744 4745
  /// Specifically, this returns true if a [Canvas] object has been
  /// created to record commands and recording has not yet ended via a
  /// call to [endRecording], and false if either this
  /// [PictureRecorder] has not yet been associated with a [Canvas],
  /// or the [endRecording] method has already been called.
4746
  bool get isRecording => _canvas != null;
A
Adam Barth 已提交
4747 4748 4749 4750 4751 4752

  /// Finishes recording graphical operations.
  ///
  /// Returns a picture containing the graphical operations that have been
  /// recorded thus far. After calling this function, both the picture recorder
  /// and the canvas objects are invalid and cannot be used further.
4753
  Picture endRecording() {
4754 4755
    if (_canvas == null)
      throw StateError('PictureRecorder did not start recording.');
4756 4757
    final Picture picture = Picture._();
    _endRecording(picture);
4758 4759
    _canvas!._recorder = null;
    _canvas = null;
4760 4761 4762 4763
    return picture;
  }

  void _endRecording(Picture outPicture) native 'PictureRecorder_endRecording';
4764 4765

  Canvas? _canvas;
4766
}
4767

G
Gary Qian 已提交
4768 4769 4770 4771 4772 4773 4774 4775
/// A single shadow.
///
/// Multiple shadows are stacked together in a [TextStyle].
class Shadow {
  /// Construct a shadow.
  ///
  /// The default shadow is a black shadow with zero offset and zero blur.
  /// Default shadows should be completely covered by the casting element,
4776
  /// and not be visible.
G
Gary Qian 已提交
4777 4778 4779 4780 4781 4782 4783 4784 4785
  ///
  /// Transparency should be adjusted through the [color] alpha.
  ///
  /// Shadow order matters due to compositing multiple translucent objects not
  /// being commutative.
  const Shadow({
    this.color = const Color(_kColorDefault),
    this.offset = Offset.zero,
    this.blurRadius = 0.0,
4786 4787
  }) : assert(color != null, 'Text shadow color was null.'), // ignore: unnecessary_null_comparison
       assert(offset != null, 'Text shadow offset was null.'), // ignore: unnecessary_null_comparison
G
Gary Qian 已提交
4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801
       assert(blurRadius >= 0.0, 'Text shadow blur radius should be non-negative.');

  static const int _kColorDefault = 0xFF000000;
  // Constants for shadow encoding.
  static const int _kBytesPerShadow = 16;
  static const int _kColorOffset = 0 << 2;
  static const int _kXOffset = 1 << 2;
  static const int _kYOffset = 2 << 2;
  static const int _kBlurOffset = 3 << 2;

  /// Color that the shadow will be drawn with.
  ///
  /// The shadows are shapes composited directly over the base canvas, and do not
  /// represent optical occlusion.
4802
  final Color color;
G
Gary Qian 已提交
4803 4804 4805 4806 4807 4808

  /// The displacement of the shadow from the casting element.
  ///
  /// Positive x/y offsets will shift the shadow to the right and down, while
  /// negative offsets shift the shadow to the left and up. The offsets are
  /// relative to the position of the element that is casting it.
4809
  final Offset offset;
G
Gary Qian 已提交
4810 4811

  /// The standard deviation of the Gaussian to convolve with the shadow's shape.
4812
  final double blurRadius;
G
Gary Qian 已提交
4813 4814 4815 4816 4817 4818 4819

  /// Converts a blur radius in pixels to sigmas.
  ///
  /// See the sigma argument to [MaskFilter.blur].
  ///
  // See SkBlurMask::ConvertRadiusToSigma().
  // <https://github.com/google/skia/blob/bb5b77db51d2e149ee66db284903572a5aac09be/src/effects/SkBlurMask.cpp#L23>
4820
  static double convertRadiusToSigma(double radius) {
G
Gary Qian 已提交
4821 4822 4823 4824 4825 4826
    return radius * 0.57735 + 0.5;
  }

  /// The [blurRadius] in sigmas instead of logical pixels.
  ///
  /// See the sigma argument to [MaskFilter.blur].
4827
  double get blurSigma => convertRadiusToSigma(blurRadius);
G
Gary Qian 已提交
4828 4829 4830 4831 4832 4833 4834

  /// Create the [Paint] object that corresponds to this shadow description.
  ///
  /// The [offset] is not represented in the [Paint] object.
  /// To honor this as well, the shape should be translated by [offset] before
  /// being filled using this [Paint].
  ///
4835 4836 4837 4838
  /// This class does not provide a way to disable shadows to avoid
  /// inconsistencies in shadow blur rendering, primarily as a method of
  /// reducing test flakiness. [toPaint] should be overridden in subclasses to
  /// provide this functionality.
4839
  Paint toPaint() {
G
Gary Qian 已提交
4840 4841 4842 4843 4844 4845 4846
    return Paint()
      ..color = color
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, blurSigma);
  }

  /// Returns a new shadow with its [offset] and [blurRadius] scaled by the given
  /// factor.
4847
  Shadow scale(double factor) {
G
Gary Qian 已提交
4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873
    return Shadow(
      color: color,
      offset: offset * factor,
      blurRadius: blurRadius * factor,
    );
  }

  /// Linearly interpolate between two shadows.
  ///
  /// If either shadow is null, this function linearly interpolates from a
  /// a shadow that matches the other shadow in color but has a zero
  /// offset and a zero blurRadius.
  ///
  /// {@template dart.ui.shadow.lerp}
  /// The `t` argument represents position on the timeline, with 0.0 meaning
  /// that the interpolation has not started, returning `a` (or something
  /// equivalent to `a`), 1.0 meaning that the interpolation has finished,
  /// returning `b` (or something equivalent to `b`), and values in between
  /// meaning that the interpolation is at the relevant point on the timeline
  /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
  /// 1.0, so negative values and values greater than 1.0 are valid (and can
  /// easily be generated by curves such as [Curves.elasticInOut]).
  ///
  /// Values for `t` are usually obtained from an [Animation<double>], such as
  /// an [AnimationController].
  /// {@endtemplate}
4874 4875
  static Shadow? lerp(Shadow? a, Shadow? b, double t) {
    assert(t != null); // ignore: unnecessary_null_comparison
Y
Yegor 已提交
4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886
    if (b == null) {
      if (a == null) {
        return null;
      } else {
        return a.scale(1.0 - t);
      }
    } else {
      if (a == null) {
        return b.scale(t);
      } else {
        return Shadow(
4887 4888 4889
          color: Color.lerp(a.color, b.color, t)!,
          offset: Offset.lerp(a.offset, b.offset, t)!,
          blurRadius: _lerpDouble(a.blurRadius, b.blurRadius, t),
Y
Yegor 已提交
4890 4891 4892
        );
      }
    }
G
Gary Qian 已提交
4893 4894 4895 4896 4897 4898 4899
  }

  /// Linearly interpolate between two lists of shadows.
  ///
  /// If the lists differ in length, excess items are lerped with null.
  ///
  /// {@macro dart.ui.shadow.lerp}
4900 4901
  static List<Shadow>? lerpList(List<Shadow>? a, List<Shadow>? b, double t) {
    assert(t != null); // ignore: unnecessary_null_comparison
G
Gary Qian 已提交
4902 4903
    if (a == null && b == null)
      return null;
4904 4905 4906
    a ??= <Shadow>[];
    b ??= <Shadow>[];
    final List<Shadow> result = <Shadow>[];
G
Gary Qian 已提交
4907 4908
    final int commonLength = math.min(a.length, b.length);
    for (int i = 0; i < commonLength; i += 1)
4909
      result.add(Shadow.lerp(a[i], b[i], t)!);
G
Gary Qian 已提交
4910 4911 4912 4913 4914 4915 4916 4917
    for (int i = commonLength; i < a.length; i += 1)
      result.add(a[i].scale(1.0 - t));
    for (int i = commonLength; i < b.length; i += 1)
      result.add(b[i].scale(t));
    return result;
  }

  @override
A
Alexandre Ardhuin 已提交
4918
  bool operator ==(Object other) {
G
Gary Qian 已提交
4919 4920
    if (identical(this, other))
      return true;
4921 4922 4923 4924
    return other is Shadow
        && other.color == color
        && other.offset == offset
        && other.blurRadius == blurRadius;
G
Gary Qian 已提交
4925 4926 4927
  }

  @override
4928
  int get hashCode => hashValues(color, offset, blurRadius);
G
Gary Qian 已提交
4929 4930 4931 4932

  // Serialize [shadows] into ByteData. The format is a single uint_32_t at
  // the beginning indicating the number of shadows, followed by _kBytesPerShadow
  // bytes for each shadow.
4933
  static ByteData _encodeShadows(List<Shadow>? shadows) {
G
Gary Qian 已提交
4934 4935 4936 4937 4938 4939 4940 4941 4942
    if (shadows == null)
      return ByteData(0);

    final int byteCount = shadows.length * _kBytesPerShadow;
    final ByteData shadowsData = ByteData(byteCount);

    int shadowOffset = 0;
    for (int shadowIndex = 0; shadowIndex < shadows.length; ++shadowIndex) {
      final Shadow shadow = shadows[shadowIndex];
4943 4944 4945 4946
      // TODO(yjbanov): remove the null check when the framework is migrated. While the list
      //                of shadows contains non-nullable elements, unmigrated code can still
      //                pass nulls.
      // ignore: unnecessary_null_comparison
4947 4948
      if (shadow != null) {
        shadowOffset = shadowIndex * _kBytesPerShadow;
G
Gary Qian 已提交
4949

4950 4951
        shadowsData.setInt32(_kColorOffset + shadowOffset,
          shadow.color.value ^ Shadow._kColorDefault, _kFakeHostEndian);
G
Gary Qian 已提交
4952

4953 4954
        shadowsData.setFloat32(_kXOffset + shadowOffset,
          shadow.offset.dx, _kFakeHostEndian);
G
Gary Qian 已提交
4955

4956 4957
        shadowsData.setFloat32(_kYOffset + shadowOffset,
          shadow.offset.dy, _kFakeHostEndian);
G
Gary Qian 已提交
4958

4959 4960 4961
        shadowsData.setFloat32(_kBlurOffset + shadowOffset,
          shadow.blurRadius, _kFakeHostEndian);
      }
G
Gary Qian 已提交
4962 4963 4964 4965 4966 4967
    }

    return shadowsData;
  }

  @override
4968
  String toString() => 'TextShadow($color, $offset, $blurRadius)';
G
Gary Qian 已提交
4969 4970
}

4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094
/// A handle to a read-only byte buffer that is managed by the engine.
class ImmutableBuffer extends NativeFieldWrapperClass2 {
  ImmutableBuffer._(this.length);

  /// Creates a copy of the data from a [Uint8List] suitable for internal use
  /// in the engine.
  static Future<ImmutableBuffer> fromUint8List(Uint8List list) {
    final ImmutableBuffer instance = ImmutableBuffer._(list.length);
    return _futurize((_Callback<void> callback) {
      instance._init(list, callback);
    }).then((_) => instance);
  }
  void _init(Uint8List list, _Callback<void> callback) native 'ImmutableBuffer_init';

  /// The length, in bytes, of the underlying data.
  final int length;

  /// Release the resources used by this object. The object is no longer usable
  /// after this method is called.
  void dispose() native 'ImmutableBuffer_dispose';
}

/// A descriptor of data that can be turned into an [Image] via a [Codec].
///
/// Use this class to determine the height, width, and byte size of image data
/// before decoding it.
class ImageDescriptor extends NativeFieldWrapperClass2 {
  ImageDescriptor._();

  /// Creates an image descriptor from encoded data in a supported format.
  static Future<ImageDescriptor> encoded(ImmutableBuffer buffer) {
    final ImageDescriptor descriptor = ImageDescriptor._();
    return _futurize((_Callback<void> callback) {
      return descriptor._initEncoded(buffer, callback);
    }).then((_) => descriptor);
  }
  String? _initEncoded(ImmutableBuffer buffer, _Callback<void> callback) native 'ImageDescriptor_initEncoded';

  /// Creates an image descriptor from raw image pixels.
  ///
  /// The `pixels` parameter is the pixel data in the encoding described by
  /// `format`.
  ///
  /// The `rowBytes` parameter is the number of bytes consumed by each row of
  /// pixels in the data buffer. If unspecified, it defaults to `width` multiplied
  /// by the number of bytes per pixel in the provided `format`.
  // Not async because there's no expensive work to do here.
  ImageDescriptor.raw(
    ImmutableBuffer buffer, {
    required int width,
    required int height,
    int? rowBytes,
    required PixelFormat pixelFormat,
  }) {
    _width = width;
    _height = height;
    // We only support 4 byte pixel formats in the PixelFormat enum.
    _bytesPerPixel = 4;
    _initRaw(this, buffer, width, height, rowBytes ?? -1, pixelFormat.index);
  }
  void _initRaw(ImageDescriptor outDescriptor, ImmutableBuffer buffer, int width, int height, int rowBytes, int pixelFormat) native 'ImageDescriptor_initRaw';

  int? _width;
  int _getWidth() native 'ImageDescriptor_width';
  /// The width, in pixels, of the image.
  ///
  /// On the Web, this is only supported for [raw] images.
  int get width => _width ??= _getWidth();

  int? _height;
  int _getHeight() native 'ImageDescriptor_height';
  /// The height, in pixels, of the image.
  ///
  /// On the Web, this is only supported for [raw] images.
  int get height => _height ??= _getHeight();

  int? _bytesPerPixel;
  int _getBytesPerPixel() native 'ImageDescriptor_bytesPerPixel';
  /// The number of bytes per pixel in the image.
  ///
  /// On web, this is only supported for [raw] images.
  int get bytesPerPixel => _bytesPerPixel ??= _getBytesPerPixel();

  /// Release the resources used by this object. The object is no longer usable
  /// after this method is called.
  void dispose() native 'ImageDescriptor_dispose';

  /// Creates a [Codec] object which is suitable for decoding the data in the
  /// buffer to an [Image].
  ///
  /// If only one of targetWidth or  targetHeight are specified, the other
  /// dimension will be scaled according to the aspect ratio of the supplied
  /// dimension.
  ///
  /// If either targetWidth or targetHeight is less than or equal to zero, it
  /// will be treated as if it is null.
  Future<Codec> instantiateCodec({int? targetWidth, int? targetHeight}) async {
    if (targetWidth != null && targetWidth <= 0) {
      targetWidth = null;
    }
    if (targetHeight != null && targetHeight <= 0) {
      targetHeight = null;
    }

    if (targetWidth == null && targetHeight == null) {
      targetWidth = width;
      targetHeight = height;
    } else if (targetWidth == null && targetHeight != null) {
      targetWidth = (targetHeight * (width / height)).round();
      targetHeight = targetHeight;
    } else if (targetHeight == null && targetWidth != null) {
      targetWidth = targetWidth;
      targetHeight = targetWidth ~/ (width / height);
    }
    assert(targetWidth != null);
    assert(targetHeight != null);

    final Codec codec = Codec._();
    _instantiateCodec(codec, targetWidth!, targetHeight!);
    return codec;
  }
  void _instantiateCodec(Codec outCodec, int targetWidth, int targetHeight) native 'ImageDescriptor_instantiateCodec';
}

5095
/// Generic callback signature, used by [_futurize].
5096
typedef _Callback<T> = void Function(T result);
5097 5098 5099 5100 5101

/// Signature for a method that receives a [_Callback].
///
/// Return value should be null on success, and a string error message on
/// failure.
5102
typedef _Callbacker<T> = String? Function(_Callback<T> callback);
5103 5104 5105 5106

/// Converts a method that receives a value-returning callback to a method that
/// returns a Future.
///
G
Greg Spencer 已提交
5107 5108
/// Return a [String] to cause an [Exception] to be synchronously thrown with
/// that string as a message.
5109 5110 5111
///
/// If the callback is called with null, the future completes with an error.
///
5112
/// Example usage:
5113
///
5114
/// ```dart
5115
/// typedef IntCallback = void Function(int result);
5116
///
5117
/// String _doSomethingAndCallback(IntCallback callback) {
D
Dan Field 已提交
5118
///   Timer(new Duration(seconds: 1), () { callback(1); });
5119
/// }
5120
///
5121
/// Future<int> doSomething() {
5122
///   return _futurize(_doSomethingAndCallback);
5123 5124
/// }
/// ```
5125
Future<T> _futurize<T>(_Callbacker<T> callbacker) {
D
Dan Field 已提交
5126
  final Completer<T> completer = Completer<T>.sync();
5127
  final String? error = callbacker((T t) {
5128
    if (t == null) {
D
Dan Field 已提交
5129
      completer.completeError(Exception('operation failed'));
5130 5131 5132 5133
    } else {
      completer.complete(t);
    }
  });
5134
  if (error != null)
D
Dan Field 已提交
5135
    throw Exception(error);
5136
  return completer.future;
5137
}