box_painter.dart 24.8 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;
import 'dart:sky' as sky;
import 'dart:sky' show Point, Offset, Size, Rect, Color, Paint, Path;

Adam Barth's avatar
Adam Barth committed
9
import 'package:sky/mojo/image_resource.dart';
10
import 'package:sky/src/painting/shadows.dart';
11

12 13 14 15
/// An immutable set of offsets in each of the four cardinal directions
///
/// Typically used for an offset from each of the four sides of a box. For
/// example, the padding inside a box can be represented using this class.
16
class EdgeDims {
17 18
  // TODO(abarth): Remove this constructor or rename it to EdgeDims.fromTRBL.
  /// Constructs an EdgeDims from offsets from the top, right, bottom and left
19
  const EdgeDims(this.top, this.right, this.bottom, this.left);
20 21

  /// Constructs an EdgeDims where all the offsets are value
22 23
  const EdgeDims.all(double value)
      : top = value, right = value, bottom = value, left = value;
24 25

  /// Constructs an EdgeDims with only the given values non-zero
26 27 28 29
  const EdgeDims.only({ this.top: 0.0,
                        this.right: 0.0,
                        this.bottom: 0.0,
                        this.left: 0.0 });
30 31

  /// Constructs an EdgeDims with symmetrical vertical and horizontal offsets
32 33 34 35
  const EdgeDims.symmetric({ double vertical: 0.0,
                             double horizontal: 0.0 })
    : top = vertical, left = horizontal, bottom = vertical, right = horizontal;

36
  /// The offset from the top
37
  final double top;
38 39

  /// The offset from the right
40
  final double right;
41 42

  /// The offset from the bottom
43
  final double bottom;
44 45

  /// The offset from the left
46 47
  final double left;

48 49
  bool get isNonNegative => top >= 0.0 && right >= 0.0 && bottom >= 0.0 && left >= 0.0;

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  bool operator ==(other) {
    if (identical(this, other))
      return true;
    return other is EdgeDims
        && top == other.top
        && right == other.right
        && bottom == other.bottom
        && left == other.left;
  }

  EdgeDims operator+(EdgeDims other) {
    return new EdgeDims(top + other.top,
                        right + other.right,
                        bottom + other.bottom,
                        left + other.left);
  }

  EdgeDims operator-(EdgeDims other) {
    return new EdgeDims(top - other.top,
                        right - other.right,
                        bottom - other.bottom,
                        left - other.left);
  }

74
  /// An EdgeDims with zero offsets in each direction
75 76 77 78 79 80 81 82 83 84 85 86 87
  static const EdgeDims zero = const EdgeDims(0.0, 0.0, 0.0, 0.0);

  int get hashCode {
    int value = 373;
    value = 37 * value + top.hashCode;
    value = 37 * value + left.hashCode;
    value = 37 * value + bottom.hashCode;
    value = 37 * value + right.hashCode;
    return value;
  }
  String toString() => "EdgeDims($top, $right, $bottom, $left)";
}

88
/// A side of a border of a box
89 90 91 92 93
class BorderSide {
  const BorderSide({
    this.color: const Color(0xFF000000),
    this.width: 1.0
  });
94 95

  /// The color of this side of the border
96
  final Color color;
97 98

  /// The width of this side of the border
99 100
  final double width;

101
  /// A black border side of zero width
102 103 104 105 106 107 108 109 110 111 112
  static const none = const BorderSide(width: 0.0);

  int get hashCode {
    int value = 373;
    value = 37 * value * color.hashCode;
    value = 37 * value * width.hashCode;
    return value;
  }
  String toString() => 'BorderSide($color, $width)';
}

113
/// A border of a box, comprised of four sides
114 115 116 117 118 119 120 121
class Border {
  const Border({
    this.top: BorderSide.none,
    this.right: BorderSide.none,
    this.bottom: BorderSide.none,
    this.left: BorderSide.none
  });

122
  /// A uniform border with all sides the same color and width
123 124 125 126 127 128 129
  factory Border.all({
    Color color: const Color(0xFF000000),
    double width: 1.0
  }) {
    BorderSide side = new BorderSide(color: color, width: width);
    return new Border(top: side, right: side, bottom: side, left: side);
  }
130

131
  /// The top side of this border
132
  final BorderSide top;
133 134

  /// The right side of this border
135
  final BorderSide right;
136 137

  /// The bottom side of this border
138
  final BorderSide bottom;
139 140

  /// The left side of this border
141 142
  final BorderSide left;

143
  /// The widths of the sides of this border represented as an EdgeDims
144 145 146 147
  EdgeDims get dimensions {
    return new EdgeDims(top.width, right.width, bottom.width, left.width);
  }

148 149 150 151 152 153 154 155 156 157 158
  int get hashCode {
    int value = 373;
    value = 37 * value * top.hashCode;
    value = 37 * value * right.hashCode;
    value = 37 * value * bottom.hashCode;
    value = 37 * value * left.hashCode;
    return value;
  }
  String toString() => 'Border($top, $right, $bottom, $left)';
}

159 160 161 162
/// A shadow cast by a box
///
/// Note: BoxShadow can cast non-rectangular shadows if the box is
/// non-rectangular (e.g., has a border radius or a circular shape).
163 164 165 166 167 168 169
class BoxShadow {
  const BoxShadow({
    this.color,
    this.offset,
    this.blur
  });

170
  /// The color of the shadow
171
  final Color color;
172 173

  /// The displacement of the shadow from the box
174
  final Offset offset;
175 176

  /// The standard deviation of the Gaussian to convolve with the box's shape
177 178
  final double blur;

179
  /// Returns a new box shadow with its offset and blur scaled by the given factor
180 181 182 183 184 185 186 187
  BoxShadow scale(double factor) {
    return new BoxShadow(
      color: color,
      offset: offset * factor,
      blur: blur * factor
    );
  }

188 189 190 191 192 193 194 195 196 197 198 199 200
  /// Linearly interpolate between two box shadows
  ///
  /// If either box shadow is null, this function linearly interpolates from a
  /// a box shadow that matches the other box shadow in color but has a zero
  /// offset and a zero blur.
  static BoxShadow lerp(BoxShadow a, BoxShadow b, double t) {
    if (a == null && b == null)
      return null;
    if (a == null)
      return b.scale(t);
    if (b == null)
      return a.scale(1.0 - t);
    return new BoxShadow(
Adam Barth's avatar
Adam Barth committed
201 202 203
      color: Color.lerp(a.color, b.color, t),
      offset: Offset.lerp(a.offset, b.offset, t),
      blur: sky.lerpDouble(a.blur, b.blur, t)
204 205
    );
  }
206

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  /// Linearly interpolate between two lists of box shadows
  ///
  /// If the lists differ in length, excess items are lerped with null.
  static List<BoxShadow> lerpList(List<BoxShadow> a, List<BoxShadow> b, double t) {
    if (a == null && b == null)
      return null;
    if (a == null)
      a = new List<BoxShadow>();
    if (b == null)
      b = new List<BoxShadow>();
    List<BoxShadow> result = new List<BoxShadow>();
    int commonLength = math.min(a.length, b.length);
    for (int i = 0; i < commonLength; ++i)
      result.add(BoxShadow.lerp(a[i], b[i], t));
    for (int i = commonLength; i < a.length; ++i)
      result.add(a[i].scale(1.0 - t));
    for (int i = commonLength; i < b.length; ++i)
      result.add(b[i].scale(t));
    return result;
  }
227

228
  String toString() => 'BoxShadow($color, $offset, $blur)';
229 230
}

231
/// A 2D gradient
232 233 234 235
abstract class Gradient {
  sky.Shader createShader();
}

236
/// A 2D linear gradient
237 238
class LinearGradient extends Gradient {
  LinearGradient({
239 240
    this.begin,
    this.end,
241
    this.colors,
242
    this.stops,
243
    this.tileMode: sky.TileMode.clamp
244 245 246 247 248 249
  }) {
    assert(colors.length == stops.length);
  }

  /// The point at which stop 0.0 of the gradient is placed
  final Point begin;
250

251 252 253 254 255 256
  /// The point at which stop 1.0 of the gradient is placed
  final Point end;

  /// The colors the gradient should obtain at each of the stops
  ///
  /// Note: This list must have the same length as [stops].
257
  final List<Color> colors;
258 259 260 261 262 263 264

  /// A list of values from 0.0 to 1.0 that denote fractions of the vector from start to end
  ///
  /// Note: This list must have the same length as [colors].
  final List<double> stops;

  /// How this gradient should tile the plane
265
  final sky.TileMode tileMode;
266 267

  sky.Shader createShader() {
268 269
    return new sky.Gradient.linear([begin, end], this.colors,
                                   this.stops, this.tileMode);
270 271 272
  }

  String toString() {
273
    return 'LinearGradient($begin, $end, $colors, $stops, $tileMode)';
274
  }
275 276
}

277
/// A 2D radial gradient
278 279 280 281 282
class RadialGradient extends Gradient {
  RadialGradient({
    this.center,
    this.radius,
    this.colors,
283
    this.stops,
284 285 286
    this.tileMode: sky.TileMode.clamp
  });

287
  /// The center of the gradient
288
  final Point center;
289 290

  /// The radius at which stop 1.0 is placed
291
  final double radius;
292 293 294 295

  /// The colors the gradient should obtain at each of the stops
  ///
  /// Note: This list must have the same length as [stops].
296
  final List<Color> colors;
297 298 299 300 301 302 303 304 305 306

  /// A list of values from 0.0 to 1.0 that denote concentric rings
  ///
  /// The rings are centered at [center] and have a radius equal to the value of
  /// the stop times [radius].
  ///
  /// Note: This list must have the same length as [colors].
  final List<double> stops;

  /// How this gradient should tile the plane
307
  final sky.TileMode tileMode;
308 309

  sky.Shader createShader() {
310
    return new sky.Gradient.radial(center, radius, colors, stops, tileMode);
311 312
  }

313
  String toString() {
314
    return 'RadialGradient($center, $radius, $colors, $stops, $tileMode)';
315
  }
316 317
}

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
/// How an image should be inscribed into a box
enum ImageFit {
  /// Fill the box by distorting the image's aspect ratio
  fill,

  /// As large as possible while still containing the image entirely within the box
  contain,

  /// As small as possible while still covering the entire box
  cover,

  /// Center the image within the box and discard any portions of the image that
  /// lie outside the box
  none,

  /// Center the image within the box and, if necessary, scale the image down to
  /// ensure that the image fits within the box
  scaleDown
}

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

343 344
  /// Repeat the image in the x direction until the box is filled horizontally
  repeatX,
345

346 347 348 349 350 351 352 353
  /// Repeat the image in the y direction until the box is filled vertically
  repeatY,

  /// Leave uncovered poritions of the box transparent
  noRepeat
}

/// Paint an image into the given rectangle in the canvas
354 355 356 357 358 359
void paintImage({
  sky.Canvas canvas,
  Rect rect,
  sky.Image image,
  sky.ColorFilter colorFilter,
  fit: ImageFit.scaleDown,
360 361 362
  repeat: ImageRepeat.noRepeat,
  double positionX: 0.5,
  double positionY: 0.5
363 364 365
}) {
  Size bounds = rect.size;
  Size imageSize = new Size(image.width.toDouble(), image.height.toDouble());
366 367
  Size sourceSize;
  Size destinationSize;
368 369
  switch(fit) {
    case ImageFit.fill:
370 371
      sourceSize = imageSize;
      destinationSize = bounds;
372 373
      break;
    case ImageFit.contain:
374 375 376 377 378
      sourceSize = imageSize;
      if (bounds.width / bounds.height > sourceSize.width / sourceSize.height)
        destinationSize = new Size(sourceSize.width * bounds.height / sourceSize.height, bounds.height);
      else
        destinationSize = new Size(bounds.width, sourceSize.height * bounds.width / sourceSize.width);
379 380
      break;
    case ImageFit.cover:
381 382 383 384 385
      if (bounds.width / bounds.height > imageSize.width / imageSize.height)
        sourceSize = new Size(imageSize.width, imageSize.width * bounds.height / bounds.width);
      else
        sourceSize = new Size(imageSize.height * bounds.width / bounds.height, imageSize.height);
      destinationSize = bounds;
386 387
      break;
    case ImageFit.none:
388 389 390
      sourceSize = new Size(math.min(imageSize.width, bounds.width),
                            math.min(imageSize.height, bounds.height));
      destinationSize = sourceSize;
391 392
      break;
    case ImageFit.scaleDown:
393 394 395 396 397 398
      sourceSize = imageSize;
      destinationSize = bounds;
      if (sourceSize.height > destinationSize.height)
        destinationSize = new Size(sourceSize.width * destinationSize.height / sourceSize.height, sourceSize.height);
      if (sourceSize.width > destinationSize.width)
        destinationSize = new Size(destinationSize.width, sourceSize.height * destinationSize.width / sourceSize.width);
399 400 401 402 403
      break;
  }
  // TODO(abarth): Implement |repeat|.
  Paint paint = new Paint();
  if (colorFilter != null)
404
    paint.colorFilter = colorFilter;
405 406 407 408
  double dx = (bounds.width - destinationSize.width) * positionX;
  double dy = (bounds.height - destinationSize.height) * positionY;
  Point destinationPosition = rect.topLeft + new Offset(dx, dy);
  canvas.drawImageRect(image, Point.origin & sourceSize, destinationPosition & destinationSize, paint);
409
}
410

411
typedef void BackgroundImageChangeListener();
412

413
/// A background image for a box
414
class BackgroundImage {
415
  /// How the background image should be inscribed into the box
416
  final ImageFit fit;
417 418

  /// How to paint any portions of the box not covered by the background image
419
  final ImageRepeat repeat;
420 421

  /// A color filter to apply to the background image before painting it
422 423
  final sky.ColorFilter colorFilter;

424
  BackgroundImage({
425
    ImageResource image,
426 427
    this.fit: ImageFit.scaleDown,
    this.repeat: ImageRepeat.noRepeat,
428
    this.colorFilter
429
  }) : _imageResource = image;
430 431

  sky.Image _image;
432
  /// The image to be painted into the background
433 434
  sky.Image get image => _image;

435
  ImageResource _imageResource;
436

437 438
  final List<BackgroundImageChangeListener> _listeners =
      new List<BackgroundImageChangeListener>();
439

440
  /// Call listener when the background images changes (e.g., arrives from the network)
441 442 443 444 445 446
  void addChangeListener(BackgroundImageChangeListener listener) {
    // We add the listener to the _imageResource first so that the first change
    // listener doesn't get callback synchronously if the image resource is
    // already resolved.
    if (_listeners.isEmpty)
      _imageResource.addListener(_handleImageChanged);
447 448 449
    _listeners.add(listener);
  }

450
  /// No longer call listener when the background image changes
451
  void removeChangeListener(BackgroundImageChangeListener listener) {
452
    _listeners.remove(listener);
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
    // We need to remove ourselves as listeners from the _imageResource so that
    // we're not kept alive by the image_cache.
    if (_listeners.isEmpty)
      _imageResource.removeListener(_handleImageChanged);
  }

  void _handleImageChanged(sky.Image resolvedImage) {
    if (resolvedImage == null)
      return;
    _image = resolvedImage;
    final List<BackgroundImageChangeListener> localListeners =
        new List<BackgroundImageChangeListener>.from(_listeners);
    for (BackgroundImageChangeListener listener in localListeners) {
      listener();
    }
468 469 470 471 472
  }

  String toString() => 'BackgroundImage($fit, $repeat)';
}

473 474 475 476 477 478 479 480 481
// TODO(abarth): Rename to BoxShape?
/// A 2D geometrical shape
enum Shape {
  /// An axis-aligned, 2D rectangle
  rectangle,

  /// A 2D locus of points equidistant from a single point
  circle
}
482

483
/// An immutable description of how to paint a box
484 485 486 487 488 489 490 491 492 493 494
class BoxDecoration {
  const BoxDecoration({
    this.backgroundColor, // null = don't draw background color
    this.backgroundImage, // null = don't draw background image
    this.border, // null = don't draw border
    this.borderRadius, // null = use more efficient background drawing; note that this must be null for circles
    this.boxShadow, // null = don't draw shadows
    this.gradient, // null = don't allocate gradient objects
    this.shape: Shape.rectangle
  });

495 496 497 498
  /// The color to fill in the background of the box
  ///
  /// The color is filled into the shape of the box (e.g., either a rectangle,
  /// potentially with a border radius, or a circle).
499
  final Color backgroundColor;
500 501

  /// An image to paint above the background color
502
  final BackgroundImage backgroundImage;
503 504

  /// A border to draw above the background
505
  final Border border;
506 507 508 509 510 511 512

  /// If non-null, the corners of this box are rounded by this radius
  ///
  /// Applies only to boxes with rectangular shapes.
  final double borderRadius;

  /// A list of shadows cast by this box behind the background
513
  final List<BoxShadow> boxShadow;
514 515

  /// A graident to use when filling the background
516
  final Gradient gradient;
517 518

  /// The shape to fill the background color into and to cast as a shadow
519 520
  final Shape shape;

521
  /// Returns a new box decoration that is scalled by the given factor
522 523 524
  BoxDecoration scale(double factor) {
    // TODO(abarth): Scale ALL the things.
    return new BoxDecoration(
Adam Barth's avatar
Adam Barth committed
525
      backgroundColor: Color.lerp(null, backgroundColor, factor),
526 527
      backgroundImage: backgroundImage,
      border: border,
Adam Barth's avatar
Adam Barth committed
528
      borderRadius: sky.lerpDouble(null, borderRadius, factor),
529
      boxShadow: BoxShadow.lerpList(null, boxShadow, factor),
530 531 532 533 534
      gradient: gradient,
      shape: shape
    );
  }

535 536 537 538 539 540 541 542 543 544 545 546
  /// Linearly interpolate between two box decorations
  ///
  /// Interpolates each parameter of the box decoration separately.
  static BoxDecoration lerp(BoxDecoration a, BoxDecoration b, double t) {
    if (a == null && b == null)
      return null;
    if (a == null)
      return b.scale(t);
    if (b == null)
      return a.scale(1.0 - t);
    // TODO(abarth): lerp ALL the fields.
    return new BoxDecoration(
Adam Barth's avatar
Adam Barth committed
547
      backgroundColor: Color.lerp(a.backgroundColor, b.backgroundColor, t),
548 549
      backgroundImage: b.backgroundImage,
      border: b.border,
Adam Barth's avatar
Adam Barth committed
550
      borderRadius: sky.lerpDouble(a.borderRadius, b.borderRadius, t),
551 552 553 554 555 556
      boxShadow: BoxShadow.lerpList(a.boxShadow, b.boxShadow, t),
      gradient: b.gradient,
      shape: b.shape
    );
  }

557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
  String toString([String prefix = '']) {
    List<String> result = [];
    if (backgroundColor != null)
      result.add('${prefix}backgroundColor: $backgroundColor');
    if (backgroundImage != null)
      result.add('${prefix}backgroundImage: $backgroundImage');
    if (border != null)
      result.add('${prefix}border: $border');
    if (borderRadius != null)
      result.add('${prefix}borderRadius: $borderRadius');
    if (boxShadow != null)
      result.add('${prefix}boxShadow: ${boxShadow.map((shadow) => shadow.toString())}');
    if (gradient != null)
      result.add('${prefix}gradient: $gradient');
    if (shape != Shape.rectangle)
      result.add('${prefix}shape: $shape');
    if (result.isEmpty)
      return '${prefix}<no decorations specified>';
    return result.join('\n');
  }
}

579
/// An object that paints a [BoxDecoration] into a canvas
580 581 582 583 584 585
class BoxPainter {
  BoxPainter(BoxDecoration decoration) : _decoration = decoration {
    assert(decoration != null);
  }

  BoxDecoration _decoration;
586
  /// The box decoration to paint
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
  BoxDecoration get decoration => _decoration;
  void set decoration (BoxDecoration value) {
    assert(value != null);
    if (value == _decoration)
      return;
    _decoration = value;
    _cachedBackgroundPaint = null;
  }

  Paint _cachedBackgroundPaint;
  Paint get _backgroundPaint {
    if (_cachedBackgroundPaint == null) {
      Paint paint = new Paint();

      if (_decoration.backgroundColor != null)
        paint.color = _decoration.backgroundColor;

      if (_decoration.boxShadow != null) {
        var builder = new ShadowDrawLooperBuilder();
        for (BoxShadow boxShadow in _decoration.boxShadow)
          builder.addShadow(boxShadow.offset, boxShadow.color, boxShadow.blur);
608
        paint.drawLooper = builder.build();
609 610 611
      }

      if (_decoration.gradient != null)
612
        paint.shader = _decoration.gradient.createShader();
613 614 615 616 617 618 619

      _cachedBackgroundPaint = paint;
    }

    return _cachedBackgroundPaint;
  }

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
  bool get _hasUniformBorder {
    Color color = _decoration.border.top.color;
    bool hasUniformColor =
      _decoration.border.right.color == color &&
      _decoration.border.bottom.color == color &&
      _decoration.border.left.color == color;

    if (!hasUniformColor)
      return false;

    double width = _decoration.border.top.width;
    bool hasUniformWidth =
      _decoration.border.right.width == width &&
      _decoration.border.bottom.width == width &&
      _decoration.border.left.width == width;

    return hasUniformWidth;
  }

639 640 641 642
  double _getEffectiveBorderRadius(Rect rect) {
    double shortestSide = rect.shortestSide;
    // In principle, we should use shortestSide / 2.0, but we don't want to
    // run into floating point rounding errors. Instead, we just use
Adam Barth's avatar
Adam Barth committed
643
    // shortestSide and let sky.Canvas do any remaining clamping.
644 645 646
    return _decoration.borderRadius > shortestSide ? shortestSide : _decoration.borderRadius;
  }

647
  void _paintBackgroundColor(sky.Canvas canvas, Rect rect) {
648 649
    if (_decoration.backgroundColor != null ||
        _decoration.boxShadow != null ||
650 651 652 653 654 655 656 657 658
        _decoration.gradient != null) {
      switch (_decoration.shape) {
        case Shape.circle:
          assert(_decoration.borderRadius == null);
          Point center = rect.center;
          double radius = rect.shortestSide / 2.0;
          canvas.drawCircle(center, radius, _backgroundPaint);
          break;
        case Shape.rectangle:
659
          if (_decoration.borderRadius == null) {
660
            canvas.drawRect(rect, _backgroundPaint);
661 662 663 664
          } else {
            double radius = _getEffectiveBorderRadius(rect);
            canvas.drawRRect(new sky.RRect()..setRectXY(rect, radius, radius), _backgroundPaint);
          }
665 666 667 668 669 670
          break;
      }
    }
  }

  void _paintBackgroundImage(sky.Canvas canvas, Rect rect) {
671 672
    final BackgroundImage backgroundImage = _decoration.backgroundImage;
    if (backgroundImage == null)
673
      return;
674
    sky.Image image = backgroundImage.image;
675 676 677 678 679 680 681 682 683 684
    if (image == null)
      return;
    paintImage(
      canvas: canvas,
      rect: rect,
      image: image,
      colorFilter: backgroundImage.colorFilter,
      fit:  backgroundImage.fit,
      repeat: backgroundImage.repeat
    );
685 686 687 688 689 690
  }

  void _paintBorder(sky.Canvas canvas, Rect rect) {
    if (_decoration.border == null)
      return;

691 692 693 694 695 696 697 698 699
    if (_hasUniformBorder) {
      if (_decoration.borderRadius != null) {
        _paintBorderWithRadius(canvas, rect);
        return;
      }
      if (_decoration.shape == Shape.circle) {
        _paintBorderWithCircle(canvas, rect);
        return;
      }
700 701 702
    }

    assert(_decoration.borderRadius == null); // TODO(abarth): Support non-uniform rounded borders.
Adam Barth's avatar
Adam Barth committed
703
    assert(_decoration.shape == Shape.rectangle); // TODO(ianh): Support non-uniform borders on circles.
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

    assert(_decoration.border.top != null);
    assert(_decoration.border.right != null);
    assert(_decoration.border.bottom != null);
    assert(_decoration.border.left != null);

    Paint paint = new Paint();
    Path path;

    paint.color = _decoration.border.top.color;
    path = new Path();
    path.moveTo(rect.left, rect.top);
    path.lineTo(rect.left + _decoration.border.left.width, rect.top + _decoration.border.top.width);
    path.lineTo(rect.right - _decoration.border.right.width, rect.top + _decoration.border.top.width);
    path.lineTo(rect.right, rect.top);
    path.close();
    canvas.drawPath(path, paint);

    paint.color = _decoration.border.right.color;
    path = new Path();
    path.moveTo(rect.right, rect.top);
    path.lineTo(rect.right - _decoration.border.right.width, rect.top + _decoration.border.top.width);
    path.lineTo(rect.right - _decoration.border.right.width, rect.bottom - _decoration.border.bottom.width);
    path.lineTo(rect.right, rect.bottom);
    path.close();
    canvas.drawPath(path, paint);

    paint.color = _decoration.border.bottom.color;
    path = new Path();
    path.moveTo(rect.right, rect.bottom);
    path.lineTo(rect.right - _decoration.border.right.width, rect.bottom - _decoration.border.bottom.width);
    path.lineTo(rect.left + _decoration.border.left.width, rect.bottom - _decoration.border.bottom.width);
    path.lineTo(rect.left, rect.bottom);
    path.close();
    canvas.drawPath(path, paint);

    paint.color = _decoration.border.left.color;
    path = new Path();
    path.moveTo(rect.left, rect.bottom);
    path.lineTo(rect.left + _decoration.border.left.width, rect.bottom - _decoration.border.bottom.width);
    path.lineTo(rect.left + _decoration.border.left.width, rect.top + _decoration.border.top.width);
    path.lineTo(rect.left, rect.top);
    path.close();
    canvas.drawPath(path, paint);
  }

750 751
  void _paintBorderWithRadius(sky.Canvas canvas, Rect rect) {
    assert(_hasUniformBorder);
752
    assert(_decoration.shape == Shape.rectangle);
753 754
    Color color = _decoration.border.top.color;
    double width = _decoration.border.top.width;
755
    double radius = _getEffectiveBorderRadius(rect);
756 757 758 759 760 761

    sky.RRect outer = new sky.RRect()..setRectXY(rect, radius, radius);
    sky.RRect inner = new sky.RRect()..setRectXY(rect.deflate(width), radius - width, radius - width);
    canvas.drawDRRect(outer, inner, new Paint()..color = color);
  }

762 763 764 765 766
  void _paintBorderWithCircle(sky.Canvas canvas, Rect rect) {
    assert(_hasUniformBorder);
    assert(_decoration.shape == Shape.circle);
    assert(_decoration.borderRadius == null);
    double width = _decoration.border.top.width;
767 768 769
    if (width <= 0.0) {
      return;
    }
770 771 772 773 774 775 776 777 778
    Paint paint = new Paint()
      ..color = _decoration.border.top.color
      ..strokeWidth = width
      ..setStyle(sky.PaintingStyle.stroke);
    Point center = rect.center;
    double radius = (rect.shortestSide - width) / 2.0;
    canvas.drawCircle(center, radius, paint);
  }

779
  /// Paint the box decoration into the given location on the given canvas
780 781 782 783 784 785
  void paint(sky.Canvas canvas, Rect rect) {
    _paintBackgroundColor(canvas, rect);
    _paintBackgroundImage(canvas, rect);
    _paintBorder(canvas, rect);
  }
}