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

5

6
import 'dart:ui' show Canvas, Clip, Path, Paint, Rect, RRect, VoidCallback;
7

8
/// Clip utilities used by [PaintingContext].
9 10 11 12
abstract class ClipContext {
  /// The canvas on which to paint.
  Canvas get canvas;

13
  void _clipAndPaint(void Function(bool doAntiAlias) canvasClipCall, Clip clipBehavior, Rect bounds, VoidCallback painter) {
14 15 16 17 18 19 20 21 22 23 24 25 26
    assert(canvasClipCall != null);
    canvas.save();
    switch (clipBehavior) {
      case Clip.none:
        break;
      case Clip.hardEdge:
        canvasClipCall(false);
        break;
      case Clip.antiAlias:
        canvasClipCall(true);
        break;
      case Clip.antiAliasWithSaveLayer:
        canvasClipCall(true);
27
        canvas.saveLayer(bounds, Paint());
28 29 30 31 32 33 34 35 36 37 38 39 40
        break;
    }
    painter();
    if (clipBehavior == Clip.antiAliasWithSaveLayer) {
      canvas.restore();
    }
    canvas.restore();
  }

  /// Clip [canvas] with [Path] according to [Clip] and then paint. [canvas] is
  /// restored to the pre-clip status afterwards.
  ///
  /// `bounds` is the saveLayer bounds used for [Clip.antiAliasWithSaveLayer].
41
  void clipPathAndPaint(Path path, Clip clipBehavior, Rect bounds, VoidCallback painter) {
42 43 44
    _clipAndPaint((bool doAntiAias) => canvas.clipPath(path, doAntiAlias: doAntiAias), clipBehavior, bounds, painter);
  }

45
  /// Clip [canvas] with [Path] according to `rrect` and then paint. [canvas] is
46 47 48
  /// restored to the pre-clip status afterwards.
  ///
  /// `bounds` is the saveLayer bounds used for [Clip.antiAliasWithSaveLayer].
49
  void clipRRectAndPaint(RRect rrect, Clip clipBehavior, Rect bounds, VoidCallback painter) {
50 51 52
    _clipAndPaint((bool doAntiAias) => canvas.clipRRect(rrect, doAntiAlias: doAntiAias), clipBehavior, bounds, painter);
  }

53
  /// Clip [canvas] with [Path] according to `rect` and then paint. [canvas] is
54 55 56
  /// restored to the pre-clip status afterwards.
  ///
  /// `bounds` is the saveLayer bounds used for [Clip.antiAliasWithSaveLayer].
57
  void clipRectAndPaint(Rect rect, Clip clipBehavior, Rect bounds, VoidCallback painter) {
58 59 60
    _clipAndPaint((bool doAntiAias) => canvas.clipRect(rect, doAntiAlias: doAntiAias), clipBehavior, bounds, painter);
  }
}