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

5
import 'dart:ui' as ui show Image;
6

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

9 10
import 'box.dart';
import 'object.dart';
11

12
export 'package:flutter/painting.dart' show
13
  BoxFit,
14 15
  ImageRepeat;

16
/// An image in the render tree.
17 18
///
/// The render image attempts to find a size for itself that fits in the given
19
/// constraints and preserves the image's intrinsic aspect ratio.
20 21 22
///
/// The image is painted using [paintImage], which describes the meanings of the
/// various fields on this class in more detail.
23
class RenderImage extends RenderBox {
24
  /// Creates a render box that displays an image.
Ian Hickson's avatar
Ian Hickson committed
25
  ///
26
  /// The [scale], [alignment], [repeat], [matchTextDirection] and [filterQuality] arguments
Ian Hickson's avatar
Ian Hickson committed
27 28
  /// must not be null. The [textDirection] argument must not be null if
  /// [alignment] will need resolving or if [matchTextDirection] is true.
29
  RenderImage({
30
    ui.Image? image,
31
    this.debugImageLabel,
32 33
    double? width,
    double? height,
34
    double scale = 1.0,
35
    Color? color,
36
    Animation<double>? opacity,
37 38
    BlendMode? colorBlendMode,
    BoxFit? fit,
39 40
    AlignmentGeometry alignment = Alignment.center,
    ImageRepeat repeat = ImageRepeat.noRepeat,
41
    Rect? centerSlice,
42
    bool matchTextDirection = false,
43
    TextDirection? textDirection,
44
    bool invertColors = false,
45
    bool isAntiAlias = false,
46
    FilterQuality filterQuality = FilterQuality.low,
47
  }) : _image = image,
Ian Hickson's avatar
Ian Hickson committed
48 49 50 51
       _width = width,
       _height = height,
       _scale = scale,
       _color = color,
52
       _opacity = opacity,
Ian Hickson's avatar
Ian Hickson committed
53 54 55 56 57 58
       _colorBlendMode = colorBlendMode,
       _fit = fit,
       _alignment = alignment,
       _repeat = repeat,
       _centerSlice = centerSlice,
       _matchTextDirection = matchTextDirection,
59
       _invertColors = invertColors,
60
       _textDirection = textDirection,
61
       _isAntiAlias = isAntiAlias,
62
       _filterQuality = filterQuality {
Adam Barth's avatar
Adam Barth committed
63 64
    _updateColorFilter();
  }
65

66 67
  Alignment? _resolvedAlignment;
  bool? _flipHorizontally;
Ian Hickson's avatar
Ian Hickson committed
68 69

  void _resolve() {
70
    if (_resolvedAlignment != null) {
Ian Hickson's avatar
Ian Hickson committed
71
      return;
72
    }
Ian Hickson's avatar
Ian Hickson committed
73 74 75 76 77 78 79 80 81 82
    _resolvedAlignment = alignment.resolve(textDirection);
    _flipHorizontally = matchTextDirection && textDirection == TextDirection.rtl;
  }

  void _markNeedResolution() {
    _resolvedAlignment = null;
    _flipHorizontally = null;
    markNeedsPaint();
  }

83
  /// The image to display.
84 85 86
  ui.Image? get image => _image;
  ui.Image? _image;
  set image(ui.Image? value) {
87
    if (value == _image) {
88
      return;
89 90 91 92 93 94 95 96
    }
    // If we get a clone of our image, it's the same underlying native data -
    // dispose of the new clone and return early.
    if (value != null && _image != null && value.isCloneOf(_image!)) {
      value.dispose();
      return;
    }
    _image?.dispose();
97 98
    _image = value;
    markNeedsPaint();
99
    if (_width == null || _height == null) {
100
      markNeedsLayout();
101
    }
102 103
  }

104
  /// A string used to identify the source of the image.
105
  String? debugImageLabel;
106

107
  /// If non-null, requires the image to have this width.
108 109 110
  ///
  /// If null, the image will pick a size that best preserves its intrinsic
  /// aspect ratio.
111 112 113
  double? get width => _width;
  double? _width;
  set width(double? value) {
114
    if (value == _width) {
115
      return;
116
    }
117 118 119 120
    _width = value;
    markNeedsLayout();
  }

121 122 123 124
  /// If non-null, require the image to have this height.
  ///
  /// If null, the image will pick a size that best preserves its intrinsic
  /// aspect ratio.
125 126 127
  double? get height => _height;
  double? _height;
  set height(double? value) {
128
    if (value == _height) {
129
      return;
130
    }
131 132 133 134
    _height = value;
    markNeedsLayout();
  }

135
  /// Specifies the image's scale.
136 137 138 139
  ///
  /// Used when determining the best display size for the image.
  double get scale => _scale;
  double _scale;
140
  set scale(double value) {
141
    if (value == _scale) {
142
      return;
143
    }
144 145 146 147
    _scale = value;
    markNeedsLayout();
  }

148
  ColorFilter? _colorFilter;
Adam Barth's avatar
Adam Barth committed
149 150

  void _updateColorFilter() {
151
    if (_color == null) {
Adam Barth's avatar
Adam Barth committed
152
      _colorFilter = null;
153
    } else {
154
      _colorFilter = ColorFilter.mode(_color!, _colorBlendMode ?? BlendMode.srcIn);
155
    }
Adam Barth's avatar
Adam Barth committed
156 157
  }

158
  /// If non-null, this color is blended with each image pixel using [colorBlendMode].
159 160 161
  Color? get color => _color;
  Color? _color;
  set color(Color? value) {
162
    if (value == _color) {
163
      return;
164
    }
Adam Barth's avatar
Adam Barth committed
165 166
    _color = value;
    _updateColorFilter();
167 168 169
    markNeedsPaint();
  }

170 171 172 173 174
  /// If non-null, the value from the [Animation] is multiplied with the opacity
  /// of each image pixel before painting onto the canvas.
  Animation<double>? get opacity => _opacity;
  Animation<double>? _opacity;
  set opacity(Animation<double>? value) {
175
    if (value == _opacity) {
176
      return;
177
    }
178

179
    if (attached) {
180
      _opacity?.removeListener(markNeedsPaint);
181
    }
182
    _opacity = value;
183
    if (attached) {
184
      value?.addListener(markNeedsPaint);
185
    }
186 187
  }

188 189
  /// Used to set the filterQuality of the image.
  ///
190 191 192 193 194 195
  /// Use the [FilterQuality.low] quality setting to scale the image, which corresponds to
  /// bilinear interpolation, rather than the default [FilterQuality.none] which corresponds
  /// to nearest-neighbor.
  FilterQuality get filterQuality => _filterQuality;
  FilterQuality _filterQuality;
  set filterQuality(FilterQuality value) {
196
    if (value == _filterQuality) {
197
      return;
198
    }
199 200 201 202 203
    _filterQuality = value;
    markNeedsPaint();
  }


204 205 206 207 208 209 210 211
  /// Used to combine [color] with this image.
  ///
  /// The default is [BlendMode.srcIn]. In terms of the blend mode, [color] is
  /// the source and this image is the destination.
  ///
  /// See also:
  ///
  ///  * [BlendMode], which includes an illustration of the effect of each blend mode.
212 213 214
  BlendMode? get colorBlendMode => _colorBlendMode;
  BlendMode? _colorBlendMode;
  set colorBlendMode(BlendMode? value) {
215
    if (value == _colorBlendMode) {
216
      return;
217
    }
218
    _colorBlendMode = value;
219 220 221 222
    _updateColorFilter();
    markNeedsPaint();
  }

Adam Barth's avatar
Adam Barth committed
223
  /// How to inscribe the image into the space allocated during layout.
224 225 226
  ///
  /// The default varies based on the other fields. See the discussion at
  /// [paintImage].
227 228 229
  BoxFit? get fit => _fit;
  BoxFit? _fit;
  set fit(BoxFit? value) {
230
    if (value == _fit) {
231
      return;
232
    }
233 234 235 236
    _fit = value;
    markNeedsPaint();
  }

237
  /// How to align the image within its bounds.
Ian Hickson's avatar
Ian Hickson committed
238 239 240
  ///
  /// If this is set to a text-direction-dependent value, [textDirection] must
  /// not be null.
241 242 243
  AlignmentGeometry get alignment => _alignment;
  AlignmentGeometry _alignment;
  set alignment(AlignmentGeometry value) {
244
    if (value == _alignment) {
245
      return;
246
    }
247
    _alignment = value;
Ian Hickson's avatar
Ian Hickson committed
248
    _markNeedResolution();
249 250
  }

251
  /// How to repeat this image if it doesn't fill its layout bounds.
252
  ImageRepeat get repeat => _repeat;
253
  ImageRepeat _repeat;
254
  set repeat(ImageRepeat value) {
255
    if (value == _repeat) {
256
      return;
257
    }
258 259 260 261
    _repeat = value;
    markNeedsPaint();
  }

262 263 264 265 266 267 268
  /// The center slice for a nine-patch image.
  ///
  /// The region of the image inside the center slice will be stretched both
  /// horizontally and vertically to fit the image into its destination. The
  /// region of the image above and below the center slice will be stretched
  /// only horizontally and the region of the image to the left and right of
  /// the center slice will be stretched only vertically.
269 270 271
  Rect? get centerSlice => _centerSlice;
  Rect? _centerSlice;
  set centerSlice(Rect? value) {
272
    if (value == _centerSlice) {
273
      return;
274
    }
275 276 277 278
    _centerSlice = value;
    markNeedsPaint();
  }

279 280
  /// Whether to invert the colors of the image.
  ///
281
  /// Inverting the colors of an image applies a new color filter to the paint.
282 283 284 285 286
  /// If there is another specified color filter, the invert will be applied
  /// after it. This is primarily used for implementing smart invert on iOS.
  bool get invertColors => _invertColors;
  bool _invertColors;
  set invertColors(bool value) {
287
    if (value == _invertColors) {
288
      return;
289
    }
290 291 292 293
    _invertColors = value;
    markNeedsPaint();
  }

Ian Hickson's avatar
Ian Hickson committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
  /// Whether to paint the image in the direction of the [TextDirection].
  ///
  /// If this is true, then in [TextDirection.ltr] contexts, the image will be
  /// drawn with its origin in the top left (the "normal" painting direction for
  /// images); and in [TextDirection.rtl] contexts, the image will be drawn with
  /// a scaling factor of -1 in the horizontal direction so that the origin is
  /// in the top right.
  ///
  /// This is occasionally used with images in right-to-left environments, for
  /// images that were designed for left-to-right locales. Be careful, when
  /// using this, to not flip images with integral shadows, text, or other
  /// effects that will look incorrect when flipped.
  ///
  /// If this is set to true, [textDirection] must not be null.
  bool get matchTextDirection => _matchTextDirection;
  bool _matchTextDirection;
  set matchTextDirection(bool value) {
311
    if (value == _matchTextDirection) {
Ian Hickson's avatar
Ian Hickson committed
312
      return;
313
    }
Ian Hickson's avatar
Ian Hickson committed
314 315 316 317 318 319 320 321 322
    _matchTextDirection = value;
    _markNeedResolution();
  }

  /// The text direction with which to resolve [alignment].
  ///
  /// This may be changed to null, but only after the [alignment] and
  /// [matchTextDirection] properties have been changed to values that do not
  /// depend on the direction.
323 324 325
  TextDirection? get textDirection => _textDirection;
  TextDirection? _textDirection;
  set textDirection(TextDirection? value) {
326
    if (_textDirection == value) {
Ian Hickson's avatar
Ian Hickson committed
327
      return;
328
    }
Ian Hickson's avatar
Ian Hickson committed
329 330 331 332
    _textDirection = value;
    _markNeedResolution();
  }

333 334 335 336 337 338 339 340 341 342 343 344 345
  /// Whether to paint the image with anti-aliasing.
  ///
  /// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
  bool get isAntiAlias => _isAntiAlias;
  bool _isAntiAlias;
  set isAntiAlias(bool value) {
    if (_isAntiAlias == value) {
      return;
    }
    _isAntiAlias = value;
    markNeedsPaint();
  }

346
  /// Find a size for the render image within the given constraints.
347 348
  ///
  ///  - The dimensions of the RenderImage must fit within the constraints.
349
  ///  - The aspect ratio of the RenderImage matches the intrinsic aspect
350 351 352
  ///    ratio of the image.
  ///  - The RenderImage's dimension are maximal subject to being smaller than
  ///    the intrinsic size of the image.
353
  Size _sizeForConstraints(BoxConstraints constraints) {
354
    // Folds the given |width| and |height| into |constraints| so they can all
355
    // be treated uniformly.
356
    constraints = BoxConstraints.tightFor(
357
      width: _width,
358
      height: _height,
359
    ).enforce(constraints);
360

361
    if (_image == null) {
362
      return constraints.smallest;
363
    }
364

365
    return constraints.constrainSizeAndAttemptToPreserveAspectRatio(Size(
366 367
      _image!.width.toDouble() / _scale,
      _image!.height.toDouble() / _scale,
Adam Barth's avatar
Adam Barth committed
368
    ));
369 370
  }

371
  @override
372
  double computeMinIntrinsicWidth(double height) {
373
    assert(height >= 0.0);
374
    if (_width == null && _height == null) {
375
      return 0.0;
376
    }
377
    return _sizeForConstraints(BoxConstraints.tightForFinite(height: height)).width;
378 379
  }

380
  @override
381
  double computeMaxIntrinsicWidth(double height) {
382
    assert(height >= 0.0);
383
    return _sizeForConstraints(BoxConstraints.tightForFinite(height: height)).width;
384 385
  }

386
  @override
387
  double computeMinIntrinsicHeight(double width) {
388
    assert(width >= 0.0);
389
    if (_width == null && _height == null) {
390
      return 0.0;
391
    }
392
    return _sizeForConstraints(BoxConstraints.tightForFinite(width: width)).height;
393 394
  }

395
  @override
396
  double computeMaxIntrinsicHeight(double width) {
397
    assert(width >= 0.0);
398
    return _sizeForConstraints(BoxConstraints.tightForFinite(width: width)).height;
399 400
  }

401
  @override
402
  bool hitTestSelf(Offset position) => true;
Adam Barth's avatar
Adam Barth committed
403

404 405 406 407 408
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return _sizeForConstraints(constraints);
  }

409
  @override
410 411 412 413
  void performLayout() {
    size = _sizeForConstraints(constraints);
  }

414 415 416 417 418 419 420 421 422 423 424 425
  @override
  void attach(covariant PipelineOwner owner) {
    super.attach(owner);
    _opacity?.addListener(markNeedsPaint);
  }

  @override
  void detach() {
    _opacity?.removeListener(markNeedsPaint);
    super.detach();
  }

426
  @override
427
  void paint(PaintingContext context, Offset offset) {
428
    if (_image == null) {
429
      return;
430
    }
Ian Hickson's avatar
Ian Hickson committed
431 432 433
    _resolve();
    assert(_resolvedAlignment != null);
    assert(_flipHorizontally != null);
434 435 436
    paintImage(
      canvas: context.canvas,
      rect: offset & size,
437
      image: _image!,
438
      debugImageLabel: debugImageLabel,
439
      scale: _scale,
440
      opacity: _opacity?.value ?? 1.0,
441 442
      colorFilter: _colorFilter,
      fit: _fit,
443
      alignment: _resolvedAlignment!,
444
      centerSlice: _centerSlice,
Ian Hickson's avatar
Ian Hickson committed
445
      repeat: _repeat,
446
      flipHorizontally: _flipHorizontally!,
447
      invertColors: invertColors,
448
      filterQuality: _filterQuality,
449
      isAntiAlias: _isAntiAlias,
450 451 452
    );
  }

453 454 455 456 457 458 459
  @override
  void dispose() {
    _image?.dispose();
    _image = null;
    super.dispose();
  }

460
  @override
461 462
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
463 464 465 466
    properties.add(DiagnosticsProperty<ui.Image>('image', image));
    properties.add(DoubleProperty('width', width, defaultValue: null));
    properties.add(DoubleProperty('height', height, defaultValue: null));
    properties.add(DoubleProperty('scale', scale, defaultValue: 1.0));
467
    properties.add(ColorProperty('color', color, defaultValue: null));
468
    properties.add(DiagnosticsProperty<Animation<double>?>('opacity', opacity, defaultValue: null));
469 470 471 472 473 474 475
    properties.add(EnumProperty<BlendMode>('colorBlendMode', colorBlendMode, defaultValue: null));
    properties.add(EnumProperty<BoxFit>('fit', fit, defaultValue: null));
    properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null));
    properties.add(EnumProperty<ImageRepeat>('repeat', repeat, defaultValue: ImageRepeat.noRepeat));
    properties.add(DiagnosticsProperty<Rect>('centerSlice', centerSlice, defaultValue: null));
    properties.add(FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction'));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
476
    properties.add(DiagnosticsProperty<bool>('invertColors', invertColors));
477
    properties.add(EnumProperty<FilterQuality>('filterQuality', filterQuality));
478
  }
479
}