decoration.dart 20.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 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 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
/*
 * Copyright (C) 2017, David PHAM-VAN <dev.nfet.net@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'dart:math' as math;

import 'package:image/image.dart' as im;
import 'package:meta/meta.dart';
import 'package:pdf/pdf.dart';
import 'package:vector_math/vector_math_64.dart';

import 'basic.dart';
import 'geometry.dart';
import 'image_provider.dart';
import 'widget.dart';

enum DecorationPosition { background, foreground }

enum BorderStyle { none, solid, dashed, dotted }

@immutable
class BoxBorder {
  const BoxBorder({
    this.left = false,
    this.top = false,
    this.right = false,
    this.bottom = false,
    this.color = PdfColors.black,
    this.width = 1.0,
    this.style = BorderStyle.solid,
  })  : assert(color != null),
        assert(width != null),
        assert(width >= 0.0),
        assert(style != null);

  final bool top;
  final bool bottom;
  final bool left;
  final bool right;

  final BorderStyle style;

  /// The color of the
  final PdfColor color;

  /// The width of the
  final double width;

  void paintRect(Context context, PdfRect box) {
    assert(box.x != null);
    assert(box.y != null);
    assert(box.width != null);
    assert(box.height != null);

    if (!(top || bottom || left || right)) {
      return;
    }

    switch (style) {
      case BorderStyle.none:
        return;
      case BorderStyle.solid:
        break;
      case BorderStyle.dashed:
        context.canvas
          ..saveContext()
          ..setLineDashPattern(const <int>[3, 3]);
        break;
      case BorderStyle.dotted:
        context.canvas
          ..saveContext()
          ..setLineDashPattern(const <int>[1, 1]);
        break;
    }

    context.canvas
      ..setStrokeColor(color)
      ..setLineWidth(width);

    if (top) {
      context.canvas.drawLine(box.x, box.top, box.right, box.top);
    }

    if (right) {
      if (!top) {
        context.canvas.moveTo(box.right, box.top);
      }
      context.canvas.lineTo(box.right, box.y);
    }

    if (bottom) {
      if (!right) {
        context.canvas.moveTo(box.right, box.y);
      }
      context.canvas.lineTo(box.x, box.y);
    }

    if (left) {
      if (!bottom) {
        context.canvas.moveTo(box.x, box.y);
        context.canvas.lineTo(box.x, box.top);
      } else if (right && top) {
        context.canvas.strokePath(close: true);
      } else {
        context.canvas.lineTo(box.x, box.top);
      }
    }

    context.canvas.strokePath();
    if (style != BorderStyle.solid) {
      context.canvas.restoreContext();
    }
  }

  void paintEllipse(Context context, PdfRect box) {
    assert(box.x != null);
    assert(box.y != null);
    assert(box.width != null);
    assert(box.height != null);

    context.canvas
      ..setStrokeColor(color)
      ..setLineWidth(width)
      ..drawEllipse(box.x + box.width / 2.0, box.y + box.height / 2.0,
          box.width / 2.0, box.height / 2.0)
      ..strokePath();
  }

  void paintRRect(Context context, PdfRect box, BorderRadius borderRadius) {
    assert(box.x != null);
    assert(box.y != null);
    assert(box.width != null);
    assert(box.height != null);

    context.canvas
      ..setStrokeColor(color)
      ..setLineWidth(width);
    borderRadius.paint(context, box);
    context.canvas.strokePath();
  }
}

/// A side of a border of a box.
class BorderSide {
  /// Creates the side of a border.
  const BorderSide({
    this.color = PdfColors.black,
    this.width = 1.0,
    this.style = BorderStyle.solid,
  });

  /// The color of this side of the border.
  final PdfColor color;

  /// The width of this side of the border.
  final double width;

  /// The style of this side of the border.
  final BorderStyle style;

  BorderSide copyWith({
    PdfColor color,
    double width,
    BorderStyle style,
  }) =>
      BorderSide(
        color: color,
        width: width,
        style: style,
      );
}

/// A border of a box, comprised of four sides: top, right, bottom, left.
class Border extends BoxBorder {
  const Border._(bool left, bool top, bool right, bool bottom, PdfColor color,
      double width, BorderStyle style)
      : super(
          left: left,
          top: top,
          right: right,
          bottom: bottom,
          color: color,
          width: width,
          style: style,
        );

  /// A uniform border with all sides the same color and width.
  factory Border.all({
    PdfColor color = PdfColors.black,
    double width = 1.0,
    BorderStyle style = BorderStyle.solid,
  }) =>
      Border._(
        true,
        true,
        true,
        true,
        color,
        width,
        style,
      );

  /// Creates a border whose sides are all the same.
  factory Border.fromBorderSide(BorderSide side) => Border.all(
        color: side.color,
        width: side.width,
        style: side.style,
      );
}

@immutable
class DecorationImage {
  @Deprecated('Use DecorationImage.provider()')
  DecorationImage({
    @required PdfImage image,
    this.fit = BoxFit.cover,
    this.alignment = Alignment.center,
  })  : assert(image != null),
        assert(fit != null),
        assert(alignment != null),
        image = ImageProxy(image),
        dpi = null;

  const DecorationImage.provider({
    @required this.image,
    this.fit = BoxFit.cover,
    this.alignment = Alignment.center,
    this.dpi,
  })  : assert(image != null),
        assert(fit != null),
        assert(alignment != null);

  final ImageProvider image;
  final BoxFit fit;
  final Alignment alignment;
  final double dpi;

  void paint(Context context, PdfRect box) {
    final _image = image.resolve(context, box.size, dpi: dpi);

    final imageSize =
        PdfPoint(_image.width.toDouble(), _image.height.toDouble());
    final sizes = applyBoxFit(fit, imageSize, box.size);
    final scaleX = sizes.destination.x / sizes.source.x;
    final scaleY = sizes.destination.y / sizes.source.y;
    final sourceRect = alignment.inscribe(
        sizes.source, PdfRect.fromPoints(PdfPoint.zero, imageSize));
    final destinationRect = alignment.inscribe(sizes.destination, box);
    final mat =
        Matrix4.translationValues(destinationRect.x, destinationRect.y, 0)
          ..scale(scaleX, scaleY, 1)
          ..translate(-sourceRect.x, -sourceRect.y);

    context.canvas
      ..saveContext()
      ..drawBox(box)
      ..clipPath()
      ..setTransform(mat)
      ..drawImage(_image, 0, 0, imageSize.x, imageSize.y)
      ..restoreContext();
  }
}

/// Defines what happens at the edge of the gradient.
enum TileMode {
  /// Edge is clamped to the final color.
  clamp,

  /// Edge is repeated from first color to last.
  // repeated,

  /// Edge is mirrored from last color to first.
  // mirror,
}

/// A 2D gradient.
@immutable
abstract class Gradient {
  /// Initialize the gradient's colors and stops.
  const Gradient({
    @required this.colors,
    this.stops,
  }) : assert(colors != null);

  final List<PdfColor> colors;

  /// A list of values from 0.0 to 1.0 that denote fractions along the gradient.
  final List<double> stops;

  void paint(Context context, PdfRect box);
}

/// A 2D linear gradient.
class LinearGradient extends Gradient {
  /// Creates a linear gradient.
  const LinearGradient({
    this.begin = Alignment.centerLeft,
    this.end = Alignment.centerRight,
    @required List<PdfColor> colors,
    List<double> stops,
    this.tileMode = TileMode.clamp,
  })  : assert(begin != null),
        assert(end != null),
        assert(tileMode != null),
        super(colors: colors, stops: stops);

  /// The offset at which stop 0.0 of the gradient is placed.
  final Alignment begin;

  /// The offset at which stop 1.0 of the gradient is placed.
  final Alignment end;

  /// How this gradient should tile the plane beyond in the region before
  final TileMode tileMode;

  @override
  void paint(Context context, PdfRect box) {
    if (colors.isEmpty) {
      return;
    }

    if (colors.length == 1) {
      context.canvas
        ..setFillColor(colors.first)
        ..fillPath();
    }

    assert(stops == null || stops.length == colors.length);

    context.canvas
      ..saveContext()
      ..clipPath()
      ..applyShader(
        PdfShading(
          context.document,
          shadingType: PdfShadingType.axial,
          boundingBox: box,
          function: PdfBaseFunction.colorsAndStops(
            context.document,
            colors,
            stops,
          ),
          start: begin.withinRect(box),
          end: end.withinRect(box),
          extendStart: true,
          extendEnd: true,
        ),
      )
      ..restoreContext();
  }
}

/// A 2D radial gradient.
class RadialGradient extends Gradient {
  /// Creates a radial gradient.
  ///
  /// The [colors] argument must not be null. If [stops] is non-null, it must
  /// have the same length as [colors].
  const RadialGradient({
    this.center = Alignment.center,
    this.radius = 0.5,
    @required List<PdfColor> colors,
    List<double> stops,
    this.tileMode = TileMode.clamp,
    this.focal,
    this.focalRadius = 0.0,
  })  : assert(center != null),
        assert(radius != null),
        assert(tileMode != null),
        assert(focalRadius != null),
        super(colors: colors, stops: stops);

  /// The center of the gradient
  final Alignment center;

  /// The radius of the gradient
  final double radius;

  /// How this gradient should tile the plane beyond the outer ring at [radius]
  /// pixels from the [center].
  final TileMode tileMode;

  /// The focal point of the gradient.
  final Alignment focal;

  /// The radius of the focal point of the gradient.
  final double focalRadius;

  @override
  void paint(Context context, PdfRect box) {
    if (colors.isEmpty) {
      return;
    }

    if (colors.length == 1) {
      context.canvas
        ..setFillColor(colors.first)
        ..fillPath();
    }

    assert(stops == null || stops.length == colors.length);

    final _focal = focal ?? center;

    final _radius = math.min(box.width, box.height);

    context.canvas
      ..saveContext()
      ..clipPath()
      ..applyShader(
        PdfShading(
          context.document,
          shadingType: PdfShadingType.radial,
          boundingBox: box,
          function: PdfBaseFunction.colorsAndStops(
            context.document,
            colors,
            stops,
          ),
          start: _focal.withinRect(box),
          end: center.withinRect(box),
          radius0: focalRadius * _radius,
          radius1: radius * _radius,
          extendStart: true,
          extendEnd: true,
        ),
      )
      ..restoreContext();
  }
}

class BoxShadow {
  const BoxShadow({
    this.color = PdfColors.black,
    this.offset = PdfPoint.zero,
    this.blurRadius = 0.0,
    this.spreadRadius = 0.0,
  });

  final PdfColor color;
  final PdfPoint offset;
  final double blurRadius;
  final double spreadRadius;

  im.Image _rect(double width, double height) {
    final shadow = im.Image(
      (width + spreadRadius * 2).round(),
      (height + spreadRadius * 2).round(),
    );

    im.fillRect(
      shadow,
      spreadRadius.round(),
      spreadRadius.round(),
      (spreadRadius + width).round(),
      (spreadRadius + height).round(),
      color.toInt(),
    );

    im.gaussianBlur(shadow, blurRadius.round());

    return shadow;
  }

  im.Image _ellipse(double width, double height) {
    final shadow = im.Image(
      (width + spreadRadius * 2).round(),
      (height + spreadRadius * 2).round(),
    );

    im.fillCircle(
      shadow,
      (spreadRadius + width / 2).round(),
      (spreadRadius + height / 2).round(),
      (width / 2).round(),
      color.toInt(),
    );

    im.gaussianBlur(shadow, blurRadius.round());

    return shadow;
  }
}

enum BoxShape { circle, rectangle }

enum PaintPhase { all, background, foreground }

/// A radius for either circular or elliptical shapes.
class Radius {
  /// Constructs a circular radius. [x] and [y] will have the same radius value.
  const Radius.circular(double radius) : this.elliptical(radius, radius);

  /// Constructs an elliptical radius with the given radii.
  const Radius.elliptical(this.x, this.y);

  /// The radius value on the horizontal axis.
  final double x;

  /// The radius value on the vertical axis.
  final double y;

  /// A radius with [x] and [y] values set to zero.
  static const Radius zero = Radius.circular(0.0);
}

/// An immutable set of radii for each corner of a rectangle.
class BorderRadius {
  /// Creates a border radius where all radii are [radius].
  const BorderRadius.all(Radius radius)
      : this.only(
          topLeft: radius,
          topRight: radius,
          bottomLeft: radius,
          bottomRight: radius,
        );

  /// Creates a border radius where all radii are [Radius.circular(radius)].
  BorderRadius.circular(double radius)
      : this.all(
          Radius.circular(radius),
        );

  /// Creates a vertically symmetric border radius where the top and bottom
  /// sides of the rectangle have the same radii.
  const BorderRadius.vertical({
    Radius top = Radius.zero,
    Radius bottom = Radius.zero,
  }) : this.only(
          topLeft: top,
          topRight: top,
          bottomLeft: bottom,
          bottomRight: bottom,
        );

  /// Creates a horizontally symmetrical border radius where the left and right
  /// sides of the rectangle have the same radii.
  const BorderRadius.horizontal({
    Radius left = Radius.zero,
    Radius right = Radius.zero,
  }) : this.only(
          topLeft: left,
          topRight: right,
          bottomLeft: left,
          bottomRight: right,
        );

  /// Creates a border radius with only the given non-zero values. The other
  /// corners will be right angles.
  const BorderRadius.only({
    this.topLeft = Radius.zero,
    this.topRight = Radius.zero,
    this.bottomLeft = Radius.zero,
    this.bottomRight = Radius.zero,
  });

  /// A border radius with all zero radii.
  static const BorderRadius zero = BorderRadius.all(Radius.zero);

  /// The top-left [Radius].
  final Radius topLeft;

  /// The top-right [Radius].
  final Radius topRight;

  /// The bottom-left [Radius].
  final Radius bottomLeft;

  /// The bottom-right [Radius].
  final Radius bottomRight;

  void paint(Context context, PdfRect box) {
    // Ellipse 4-spline magic number
    const _m4 = 0.551784;

    context.canvas
      // Start
      ..moveTo(box.x, box.y + bottomLeft.y)
      // bottomLeft
      ..curveTo(
          box.x,
          box.y - _m4 * bottomLeft.y + bottomLeft.y,
          box.x - _m4 * bottomLeft.x + bottomLeft.x,
          box.y,
          box.x + bottomLeft.x,
          box.y)
      // bottom
      ..lineTo(box.x + box.width - bottomRight.x, box.y)
      // bottomRight
      ..curveTo(
          box.x + _m4 * bottomRight.x + box.width - bottomRight.x,
          box.y,
          box.x + box.width,
          box.y - _m4 * bottomRight.y + bottomRight.y,
          box.x + box.width,
          box.y + bottomRight.y)
      // right
      ..lineTo(box.x + box.width, box.y + box.height - topRight.y)
      // topRight
      ..curveTo(
          box.x + box.width,
          box.y + _m4 * topRight.y + box.height - topRight.y,
          box.x + _m4 * topRight.x + box.width - topRight.x,
          box.y + box.height,
          box.x + box.width - topRight.x,
          box.y + box.height)
      // top
      ..lineTo(box.x + topLeft.x, box.y + box.height)
      // topLeft
      ..curveTo(
          box.x - _m4 * topLeft.x + topLeft.x,
          box.y + box.height,
          box.x,
          box.y + _m4 * topLeft.y + box.height - topLeft.y,
          box.x,
          box.y + box.height - topLeft.y)
      // left
      ..lineTo(box.x, box.y + bottomLeft.y);
  }
}

@immutable
class BoxDecoration {
  const BoxDecoration({
    this.color,
    this.border,
    @Deprecated('Use borderRadiusEx with `BorderRadius.all(Radius.circular(20))`')
        double borderRadius,
    BorderRadius borderRadiusEx,
    this.boxShadow,
    this.gradient,
    this.image,
    this.shape = BoxShape.rectangle,
  })  : assert(shape != null),
        assert(!(borderRadius != null && borderRadiusEx != null),
            'Don\'t set both borderRadius and borderRadiusEx'),
        _borderRadius = borderRadiusEx,
        _radius = borderRadius;

  /// The color to fill in the background of the box.
  final PdfColor color;
  final BoxBorder border;
  final BorderRadius _borderRadius;
  final double _radius;
  final BoxShape shape;
  final DecorationImage image;
  final Gradient gradient;
  final List<BoxShadow> boxShadow;

  BorderRadius get borderRadius =>
      _borderRadius ??
      (_radius == null ? null : BorderRadius.all(Radius.circular(_radius)));

  void paint(
    Context context,
    PdfRect box, [
    PaintPhase phase = PaintPhase.all,
  ]) {
    assert(box.x != null);
    assert(box.y != null);
    assert(box.width != null);
    assert(box.height != null);

    if (phase == PaintPhase.all || phase == PaintPhase.background) {
      if (color != null) {
        switch (shape) {
          case BoxShape.rectangle:
            if (borderRadius == null) {
              if (boxShadow != null) {
                for (final s in boxShadow) {
                  final i = s._rect(box.width, box.height);
                  final m = PdfImage.fromImage(context.document, image: i);
                  context.canvas.drawImage(
                    m,
                    box.x + s.offset.x - s.spreadRadius,
                    box.y - s.offset.y - s.spreadRadius,
                  );
                }
              }
              context.canvas.drawBox(box);
            } else {
              if (boxShadow != null) {
                for (final s in boxShadow) {
                  final i = s._rect(box.width, box.height);
                  final m = PdfImage.fromImage(context.document, image: i);
                  context.canvas.drawImage(
                    m,
                    box.x + s.offset.x - s.spreadRadius,
                    box.y - s.offset.y - s.spreadRadius,
                  );
                }
              }
              borderRadius.paint(context, box);
            }
            break;
          case BoxShape.circle:
            if (boxShadow != null && box.width == box.height) {
              for (final s in boxShadow) {
                final i = s._ellipse(box.width, box.height);
                final m = PdfImage.fromImage(context.document, image: i);
                context.canvas.drawImage(
                  m,
                  box.x + s.offset.x - s.spreadRadius,
                  box.y - s.offset.y - s.spreadRadius,
                );
              }
            }
            context.canvas.drawEllipse(box.x + box.width / 2.0,
                box.y + box.height / 2.0, box.width / 2.0, box.height / 2.0);
            break;
        }
        context.canvas
          ..setFillColor(color)
          ..fillPath();
      }

      if (gradient != null) {
        switch (shape) {
          case BoxShape.rectangle:
            if (borderRadius == null) {
              context.canvas.drawBox(box);
            } else {
              borderRadius.paint(context, box);
            }
            break;
          case BoxShape.circle:
            context.canvas.drawEllipse(box.x + box.width / 2.0,
                box.y + box.height / 2.0, box.width / 2.0, box.height / 2.0);
            break;
        }

        gradient.paint(context, box);
      }

      if (image != null) {
        context.canvas.saveContext();
        switch (shape) {
          case BoxShape.circle:
            context.canvas
              ..drawEllipse(box.x + box.width / 2.0, box.y + box.height / 2.0,
                  box.width / 2.0, box.height / 2.0)
              ..clipPath();

            break;
          case BoxShape.rectangle:
            if (borderRadius != null) {
              borderRadius.paint(context, box);
              context.canvas.clipPath();
            }
            break;
        }
        image.paint(context, box);
        context.canvas.restoreContext();
      }
    }

    if (phase == PaintPhase.all || phase == PaintPhase.foreground) {
      if (border != null) {
        switch (shape) {
          case BoxShape.circle:
            border.paintEllipse(context, box);
            break;
          case BoxShape.rectangle:
            if (borderRadius != null) {
              border.paintRRect(context, box, borderRadius);
            } else {
              border.paintRect(context, box);
            }
            break;
        }
      }
    }
  }
}