【Flutter】绘制图形原理

Flutter长图显示,自定义显示图片的指定区域 对于这个小工具,我们反着来写,可能更加容易理解。首先我们定义一个类继承自。需求是对超长图进行自定义裁剪显示,很容易想到,我们需要哪些数据,至于数据怎么提供,我们下面再说。1.需要Image对象,包含原图片的宽高信息, 这个Image来自dart:ui中的内置对象2.需要知道裁剪的起始位置,我们用(x, y)表示, 范围都是[0,1], 比如对于y=0表示居顶;y=1表示居底;y=0.5表示中心位置。3.需要裁剪的比例,用ratio来定义。好了,把上面说的翻译一下,我们就实现了下面的代码。 阅读详情

1 Canvas画布

API名称功能
drawLine画线
drawPoint画点
drawPath画路径
drawImage画图像
drawRect画矩形
drawCircle画圆
drawOval画椭圆
drawArc画圆弧

1.0 画笔Paint

使用方法:
可以创建全局对象,通过级联增加画笔属性

  Paint _paint = Paint()
    ..color //The color to use when stroking or filling a shape.Defaults to opaque black
    ..style//Whether to paint inside shapes, the edges of shapes, or both.Defaults to PaintingStyle.fill.
    ..blendMode //A blend mode to apply when a shape is drawn or a layer is composited.
    ..colorFilter //When a shape is being drawn, colorFilter overrides color and shader.
    ..filterQuality //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.
    ..imageFilter //The ImageFilter to use when drawing raster images.
    ..invertColors //Whether the colors of the image are inverted when drawn.
    ..isAntiAlias //Whether to apply anti-aliasing to lines and images drawn on the canvas.
    ..maskFilter //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.
    ..shader //The shader to use when stroking or filling a shape.
    ..strokeCap //The kind of finish to place on the end of lines drawn when style is set to PaintingStyle.stroke.
    ..strokeJoin //The kind of finish to place on the joins between segments.
    ..strokeMiterLimit
    ..strokeWidth = 2;

源码:

/// 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 {
  // 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
  //   value of zero, but some, such as color, have a non-zero default value.
  //   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.

  final ByteData _data = ByteData(_kDataByteCount);
  static const int _kIsAntiAliasIndex = 0;
  static const int _kColorIndex = 1;
  static const int _kBlendModeIndex = 2;
  static const int _kStyleIndex = 3;
  static const int _kStrokeWidthIndex = 4;
  static const int _kStrokeCapIndex = 5;
  static const int _kStrokeJoinIndex = 6;
  static const int _kStrokeMiterLimitIndex = 7;
  static const int _kFilterQualityIndex = 8;
  static const int _kMaskFilterIndex = 9;
  static const int _kMaskFilterBlurStyleIndex = 10;
  static const int _kMaskFilterSigmaIndex = 11;
  static const int _kInvertColorIndex = 12;
  static const int _kDitherIndex = 13;

  static const int _kIsAntiAliasOffset = _kIsAntiAliasIndex << 2;
  static const int _kColorOffset = _kColorIndex << 2;
  static const int _kBlendModeOffset = _kBlendModeIndex << 2;
  static const int _kStyleOffset = _kStyleIndex << 2;
  static const int _kStrokeWidthOffset = _kStrokeWidthIndex << 2;
  static const int _kStrokeCapOffset = _kStrokeCapIndex << 2;
  static const int _kStrokeJoinOffset = _kStrokeJoinIndex << 2;
  static const int _kStrokeMiterLimitOffset = _kStrokeMiterLimitIndex << 2;
  static const int _kFilterQualityOffset = _kFilterQualityIndex << 2;
  static const int _kMaskFilterOffset = _kMaskFilterIndex << 2;
  static const int _kMaskFilterBlurStyleOffset = _kMaskFilterBlurStyleIndex << 2;
  static const int _kMaskFilterSigmaOffset = _kMaskFilterSigmaIndex << 2;
  static const int _kInvertColorOffset = _kInvertColorIndex << 2;
  static const int _kDitherOffset = _kDitherIndex << 2;
  // If you add more fields, remember to update _kDataByteCount.
  static const int _kDataByteCount = 56;

  // Binary format must match the deserialization code in paint.cc.
  List<dynamic>? _objects;

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

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

  /// Constructs an empty [Paint] object with all fields initialized to
  /// their defaults.
  Paint() {
    if (enableDithering) {
      _dither = true;
    }
  }

  /// Whether to apply anti-aliasing to lines and images drawn on the
  /// canvas.
  ///
  /// Defaults to true.
  bool get isAntiAlias {
    return _data.getInt32(_kIsAntiAliasOffset, _kFakeHostEndian) == 0;
  }
  set isAntiAlias(bool value) {
    // 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);
  }

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

  /// The color to use when stroking or filling a shape.
  ///
  /// Defaults to opaque black.
  ///
  /// 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].
  Color get color {
    final int encoded = _data.getInt32(_kColorOffset, _kFakeHostEndian);
    return Color(encoded ^ _kColorDefault);
  }
  set color(Color value) {
    assert(value != null); // ignore: unnecessary_null_comparison
    final int encoded = value.value ^ _kColorDefault;
    _data.setInt32(_kColorOffset, encoded, _kFakeHostEndian);
  }

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

  /// A blend mode to apply when a shape is drawn or a layer is composited.
  ///
  /// 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.
  ///
  /// Defaults to [BlendMode.srcOver].
  ///
  /// See also:
  ///
  ///  * [Canvas.saveLayer], which uses its [Paint]'s [blendMode] to composite
  ///    the layer when [Canvas.restore] is called.
  ///  * [BlendMode], which discusses the user of [Canvas.saveLayer] with
  ///    [blendMode].
  BlendMode get blendMode {
    final int encoded = _data.getInt32(_kBlendModeOffset, _kFakeHostEndian);
    return BlendMode.values[encoded ^ _kBlendModeDefault];
  }
  set blendMode(BlendMode value) {
    assert(value != null); // ignore: unnecessary_null_comparison
    final int encoded = value.index ^ _kBlendModeDefault;
    _data.setInt32(_kBlendModeOffset, encoded, _kFakeHostEndian);
  }

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

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

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

  /// 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].
  ///
  /// Defaults to [StrokeJoin.miter], i.e. sharp corners.
  ///
  /// Some examples of joins:
  ///
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_4_join.mp4}
  ///
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/round_join.mp4}
  ///
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/bevel_join.mp4}
  ///
  /// 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.
  StrokeJoin get strokeJoin {
    return StrokeJoin.values[_data.getInt32(_kStrokeJoinOffset, _kFakeHostEndian)];
  }
  set strokeJoin(StrokeJoin value) {
    assert(value != null); // ignore: unnecessary_null_comparison
    final int encoded = value.index;
    _data.setInt32(_kStrokeJoinOffset, encoded, _kFakeHostEndian);
  }

  // Must be kept in sync with the default in paint.cc.
  static const double _kStrokeMiterLimitDefault = 4.0;

  /// 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
  /// angle between line segments is animated, as seen in the diagrams below.
  ///
  /// 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.
  ///
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_0_join.mp4}
  ///
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_4_join.mp4}
  ///
  /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_6_join.mp4}
  ///
  /// 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.
  double get strokeMiterLimit {
    return _data.getFloat32(_kStrokeMiterLimitOffset, _kFakeHostEndian);
  }
  set strokeMiterLimit(double value) {
    assert(value != null); // ignore: unnecessary_null_comparison
    final double encoded = value - _kStrokeMiterLimitDefault;
    _data.setFloat32(_kStrokeMiterLimitOffset, encoded, _kFakeHostEndian);
  }

  /// 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.
  MaskFilter? get maskFilter {
    switch (_data.getInt32(_kMaskFilterOffset, _kFakeHostEndian)) {
      case MaskFilter._TypeNone:
        return null;
      case MaskFilter._TypeBlur:
        return MaskFilter.blur(
          BlurStyle.values[_data.getInt32(_kMaskFilterBlurStyleOffset, _kFakeHostEndian)],
          _data.getFloat32(_kMaskFilterSigmaOffset, _kFakeHostEndian),
        );
    }
    return null;
  }
  set maskFilter(MaskFilter? value) {
    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);
    }
  }

  /// 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].
  ///
  /// Defaults to [FilterQuality.none].
  // TODO(ianh): verify that the image drawing methods actually respect this
  FilterQuality get filterQuality {
    return FilterQuality.values[_data.getInt32(_kFilterQualityOffset, _kFakeHostEndian)];
  }
  set filterQuality(FilterQuality value) {
    assert(value != null); // ignore: unnecessary_null_comparison
    final int encoded = value.index;
    _data.setInt32(_kFilterQualityOffset, encoded, _kFakeHostEndian);
  }

  /// 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.
  Shader? get shader {
    return _objects?[_kShaderIndex] as Shader?;
  }
  set shader(Shader? value) {
    _ensureObjectsInitialized()[_kShaderIndex] = value;
  }

  /// 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].
  ColorFilter? get colorFilter {
    return _objects?[_kColorFilterIndex]?.creator as ColorFilter?;
  }

  set colorFilter(ColorFilter? value) {
    final _ColorFilter? nativeFilter = value?._toNativeColorFilter();
    if (nativeFilter == null) {
      if (_objects != null) {
        _objects![_kColorFilterIndex] = null;
      }
    } else {
      _ensureObjectsInitialized()[_kColorFilterIndex] = nativeFilter;
    }
  }

  /// 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.
  ImageFilter? get imageFilter {
    return _objects?[_kImageFilterIndex]?.creator as ImageFilter?;
  }

  set imageFilter(ImageFilter? value) {
    if (value == null) {
      if (_objects != null) {
        _objects![_kImageFilterIndex] = null;
      }
    } else {
      final List<dynamic> objects = _ensureObjectsInitialized();
      if (objects[_kImageFilterIndex]?.creator != value) {
        objects[_kImageFilterIndex] = value._toNativeImageFilter();
      }
    }
  }

  /// Whether the colors of the image are inverted when drawn.
  ///
  /// Inverting the colors of an image applies a new color filter that will
  /// be composed with any user provided color filters. This is primarily
  /// used for implementing smart invert on iOS.
  bool get invertColors {
    return _data.getInt32(_kInvertColorOffset, _kFakeHostEndian) == 1;
  }
  set invertColors(bool value) {
    _data.setInt32(_kInvertColorOffset, value ? 1 : 0, _kFakeHostEndian);
  }

  bool get _dither {
    return _data.getInt32(_kDitherOffset, _kFakeHostEndian) == 1;
  }
  set _dither(bool value) {
    _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.
  static bool enableDithering = false;

  @override
  String toString() {
    if (const bool.fromEnvironment('dart.vm.product', defaultValue: false)) {
      return super.toString();
    }
    final StringBuffer result = StringBuffer();
    String semicolon = '';
    result.write('Paint(');
    if (style == PaintingStyle.stroke) {
      result.write('$style');
      if (strokeWidth != 0.0)
        result.write(' ${strokeWidth.toStringAsFixed(1)}');
      else
        result.write(' hairline');
      if (strokeCap != StrokeCap.butt)
        result.write(' $strokeCap');
      if (strokeJoin == StrokeJoin.miter) {
        if (strokeMiterLimit != _kStrokeMiterLimitDefault)
          result.write(' $strokeJoin up to ${strokeMiterLimit.toStringAsFixed(1)}');
      } else {
        result.write(' $strokeJoin');
      }
      semicolon = '; ';
    }
    if (isAntiAlias != true) {
      result.write('${semicolon}antialias off');
      semicolon = '; ';
    }
    if (color != const Color(_kColorDefault)) {
      result.write('$semicolon$color');
      semicolon = '; ';
    }
    if (blendMode.index != _kBlendModeDefault) {
      result.write('$semicolon$blendMode');
      semicolon = '; ';
    }
    if (colorFilter != null) {
      result.write('${semicolon}colorFilter: $colorFilter');
      semicolon = '; ';
    }
    if (maskFilter != null) {
      result.write('${semicolon}maskFilter: $maskFilter');
      semicolon = '; ';
    }
    if (filterQuality != FilterQuality.none) {
      result.write('${semicolon}filterQuality: $filterQuality');
      semicolon = '; ';
    }
    if (shader != null) {
      result.write('${semicolon}shader: $shader');
      semicolon = '; ';
    }
    if (imageFilter != null) {
      result.write('${semicolon}imageFilter: $imageFilter');
      semicolon = '; ';
    }
    if (invertColors)
      result.write('${semicolon}invert: $invertColors');
    if (_dither)
      result.write('${semicolon}dither: $_dither');
    result.write(')');
    return result.toString();
  }
}

1.1 drawLine 画线使用方法及源码分析

使用方法:
p1和p2为线段的两个端点,使用画笔paint

//p1和p2为线段的两个端点
canvas.drawLine(p1, p2, paint);

源码:

  /// Draws a line between the given points using the given paint. The line is
  /// stroked, the value of the [Paint.style] is ignored for this call.
  ///
  /// The `p1` and `p2` arguments are interpreted as offsets from the origin.
  void drawLine(Offset p1, Offset p2, Paint paint) {
    assert(_offsetIsValid(p1));
    assert(_offsetIsValid(p2));
    assert(paint != null); // ignore: unnecessary_null_comparison
    _drawLine(p1.dx, p1.dy, p2.dx, p2.dy, paint._objects, paint._data);
  }
  void _drawLine(double x1,
                 double y1,
                 double x2,
                 double y2,
                 List<dynamic>? paintObjects,
                 ByteData paintData) native 'Canvas_drawLine';

1.2 drawPoint 画点使用方法及源码分析

使用方法:

canvas.drawPoints(pointMode, points, paint)

第一个参数 pointMode 是点的模式
示例:

PointMode.points;//点模式  
PointMode.lines; //情侣模式
PointMode.polygon; //连线模式

第二个参数 points 是点的集合
示例:

List<Offset> points = new List();
points.add(new Offset(100, 100));
points.add(new Offset(125, 200));
points.add(new Offset(50, 150));
points.add(new Offset(150, 150));
points.add(new Offset(75, 200));

第三个参数是画笔

源码:

  /// Draws a sequence of points according to the given [PointMode].
  ///
  /// The `points` argument is interpreted as offsets from the origin.
  ///
  /// See also:
  ///
  ///  * [drawRawPoints], which takes `points` as a [Float32List] rather than a
  ///    [List<Offset>].
  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
    _drawPoints(paint._objects, paint._data, pointMode.index, _encodePointList(points));
  }

1.3 drawPath 画路径使用方法及源码

使用方法:

canvas.drawPath(path, paint)

通过绘制路径的方法创建图形,示例:

Path _path = Path();
  @override
  void paint(Canvas canvas, Size size) {
    _paint.style = PaintingStyle.stroke; // 画线模式
    _path.addArc(new Rect.fromLTWH(50, 50, 50, 50), 135.0 * (pi / 180.0), 225.0 * (pi / 180.0));
    _path.addArc(new Rect.fromLTWH(100, 50, 50, 50), 180.0 * (pi / 180.0), 225.0 * (pi / 180.0));
    _path.lineTo(100, 140);
    _path.lineTo(58, 93);
    canvas.drawPath(_path, _paint);
  }

path 可以调用的方法:
①addXXX() - 添加子图形
addArc(Rect oval, double startAngle, double sweepAngle) - 添加圆弧
addOval(Rect oval) - 添加圆
addPolygon(List points, bool close) - 添加一个由点的集合描述的多边形
addRect(Rect rect) - 添加矩形
addRRect(Rect rect) - 添加圆角矩形
addPath(Path path, Offset offset) - 添加子路径
②XXXTo() - 画线(直线或曲线)
画线方法较复杂

源码:

  /// 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]).
  void drawPath(Path path, Paint paint) {
    // ignore: unnecessary_null_comparison
    assert(path != null); // path is checked on the engine side
    assert(paint != null); // ignore: unnecessary_null_comparison
    _drawPath(path, paint._objects, paint._data);
  }
  void _drawPath(Path path,
                 List<dynamic>? paintObjects,
                 ByteData paintData) native 'Canvas_drawPath';

1.4 drawImage 画图片使用方法及源码

使用方法:

canvas.drawImage(image, offset, paint)

源码:

  /// Draws the given [Image] into the canvas with its top-left corner at the
  /// given [Offset]. The image is composited into the canvas using the given [Paint].
  void drawImage(Image image, Offset offset, Paint paint) {
    // ignore: unnecessary_null_comparison
    assert(image != null); // image is checked on the engine side
    assert(_offsetIsValid(offset));
    assert(paint != null); // ignore: unnecessary_null_comparison
    _drawImage(image._image, offset.dx, offset.dy, paint._objects, paint._data);
  }
  void _drawImage(_Image image,
                  double x,
                  double y,
                  List<dynamic>? paintObjects,
                  ByteData paintData) native 'Canvas_drawImage';

1.5 drawRect 画矩形使用方法及源码

使用方法:

canvas.drawRect(rect, paint)

rect 是一个矩形参数
示例:
LTWH分别是left、top、width、height

canvas.drawRect(new Rect.fromLTWH(120, 50, 50, 50),_paint);

源码:

  /// Draws a rectangle with the given [Paint]. Whether the rectangle is filled
  /// or stroked (or both) is controlled by [Paint.style].
  void drawRect(Rect rect, Paint paint) {
    assert(_rectIsValid(rect));
    assert(paint != null); // ignore: unnecessary_null_comparison
    _drawRect(rect.left, rect.top, rect.right, rect.bottom,
              paint._objects, paint._data);
  }
  void _drawRect(double left,
                 double top,
                 double right,
                 double bottom,
                 List<dynamic>? paintObjects,
                 ByteData paintData) native 'Canvas_drawRect';

1.6 drawCircle 画园使用方法及源码

使用方法:

canvas.drawCircle(c, radius, paint)

c 为圆心的位置,radius 为圆的半径
示例:

canvas.drawCircle(new Offset(200, 200), 100, _paint);

源码:

  /// 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
  /// controlled by [Paint.style].
  void drawCircle(Offset c, double radius, Paint paint) {
    assert(_offsetIsValid(c));
    assert(paint != null); // ignore: unnecessary_null_comparison
    _drawCircle(c.dx, c.dy, radius, paint._objects, paint._data);
  }
  void _drawCircle(double x,
                   double y,
                   double radius,
                   List<dynamic>? paintObjects,
                   ByteData paintData) native 'Canvas_drawCircle';

1.7 drawOval 画椭圆使用方法及源码

使用方法:

canvas.drawOval(rect, paint)

椭圆是通过矩形规范出来的,rect是矩形的参数
示例:

canvas.drawOval(new Rect.fromLTWH(50, 50, 100, 50), _paint);

1.8 drawArc 画圆弧使用方法及源码

使用方法:

canvas.drawArc(rect, startAngle, sweepAngle, useCenter, paint)

示例:
第一个参数是一块矩形区域
第二个参数 startAngle 与第三个参数 sweepAngle 弧度制,要乘 (pi / 180.0)度
第四个参数 useCenter 代表是否与圆心连接

canvas.drawArc(new Rect.fromLTWH(50, 50, 100, 50), 200.0* (pi / 180.0), 90 * (pi / 180.0), true, _paint);

源码:

  /// 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
  /// 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].
  void drawArc(Rect rect, double startAngle, double sweepAngle, bool useCenter, Paint paint) {
    assert(_rectIsValid(rect));
    assert(paint != null); // ignore: unnecessary_null_comparison
    _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,
                List<dynamic>? paintObjects,
                ByteData paintData) native 'Canvas_drawArc';
Flutter的绘制剖析——图形库skia skia是一个航空母舰级别的图形图像库,其应用广泛并且跨平台,不仅用于Flutter和Android操作系统,还用于Google Chrome浏览器,同时支持windows、Mac、iOS操作系统。 阅读详情

相关推荐

这一篇让你彻底搞懂贝塞尔曲线的原理

贝塞尔曲线不懂画?不知道怎么回事?看这一篇就够了!用图形,点曲线运动图和公式推导,让你彻底搞懂贝塞尔曲线的运行原理!

Flutter 跨平台技术研究 741

Flutter PIP(画中画)效果的实现

前言 继续上一篇 Flutter侧滑栏及城市选择UI的实现,今天继续讲Flutter的实现篇,画中画效果的实现。先看一下PIP的实现效果. 更多效果请查看PIP DEMO 代码地址:FlutterPIP 为什么会有此文? 一天在浏览朋友圈时,发现了一个朋友发了一张图(当然不是女朋友,但是个女的),类似上面效果部分. 一看效果挺牛啊,这是怎么实现的呢?心想要不自己实现一下吧?于是开始准备用And...

dingdegao的博客 1384

CTF选手必备:Windows 10+VMware Workstation Pro打造开箱即用的CTFos虚拟机环境

本文详细介绍了如何利用Windows 10和VMware Workstation Pro快速搭建一个开箱即用的CTFos虚拟机环境,专为CTF选手设计。从硬件配置到虚拟机优化,再到工具链配置和常见问题解决,提供了一套完整的解决方案,帮助选手高效备战网络安全竞赛。

weixin_30505225的博客 475

Flutter 浅析之 自定义view (自定义图形 绘制drawImage 加载本地图片 ui.Image的使用) 四

技术无止境,只怕不学习啊,Flutter 我们开始吧 绘制drawImage的时候遇到一个问题获取要绘制的图片,查询的一些资料找出来一个方法可以回去本地图片 ,因为绘制的时候Image对象必须使用ui.Image /// 通过assets路径,获取资源图片 Future<ui.Image> load(String asset) async { ByteData data = await rootBundle.load(asset); ui.Codec codec = awa

万物weiyi 3945

OpenCV图像去畸变实战指南:从原理到参数调优(附完整代码与效果对比)

本文详细解析了OpenCV图像去畸变的原理与实战方法,对比了三种核心函数(标准、鱼眼、全景模型)的适用场景与效果。重点提供了完整的代码示例,并深入探讨了alpha、焦距、中心点等关键参数的调优技巧,以帮助开发者有效矫正镜头畸变,提升计算机视觉任务精度。

life6的博客 558

(蓝桥杯)STM32G431RBT6(SysTick timer)

选用最基础的定时器。

2301_81764359的博客 1913

Flutter图片裁剪

做app登陆的时候,需要用到图片裁剪功能,由于刚接触Flutter不久,所以就萌生了自己写一个的想法,说干就干!让我们站在巨人的肩膀上前进吧。 flutter中图片裁剪主要采用drawImageRect(Image image, Rect src, Rect dst, Paint paint)方法来从图片上抠图,介绍如下: /// Draws the subset of the given ima...

qq627578198的博客 7203

2021秋-北邮计算机导论期末考试(BUPT)

2021秋-北邮计算机导论期末考试(BUPT) 难度较低适合新手练习

weixin_73985779的博客 1541

Flutter绘制系列03---绘制图片文字

好,这样我们就将一个画板创造出来了。并且上面会有一张我们drawImage出来的图片。 好的,这样的话我们的图片就成功的在画布上渲染出来了。然后我们再来思考一个问题,我们有没有可能将这个图片给他按照矩形裁剪出来呢? 这样,我们就可以将我们的图片做各种不同的裁剪绘制了。 5、绘制图集 定义每个Sprite类封装图片元素数据 绘制一张图片 图形的变换 5、绘制原始图集: 2、 文字绘制......

title_martin的博客 2192

OC5021B 100V宽电压输入 LED车灯/大功率照明 DC降压型恒流驱动器

适用于LED大功率汽车大灯/大功率照明 OC5021B 100V宽电压输入 5A电流设计 DC-DC降压型恒流驱动IC

Handsome63841990的博客 2433

Python 爬虫实战:亚马逊商品评论 + 评分抓取(情感分析数据预处理)

在电子商务领域,用户评论是了解产品口碑和市场反馈的重要渠道。亚马逊作为全球领先的电商平台,拥有海量的商品评论数据。本文将详细介绍如何使用 Python 编写爬虫程序,从亚马逊网站抓取商品评论和评分数据,并进行情感分析的数据预处理。

yansideyucsdn的博客 776

深入理解Flutter的图形图像绘制原理——图形库skia剖析

Flutter是目前流行的高性能跨平台UI框架,图形库skia是其跨平台的基石。本文将深入分析skia的图形、字体、图片的渲染原理,如何挖掘硬件特性,为UI性能优化提供思路。 1. 引言 Flutter是目前非常流行的跨平台UI开发框架,不仅支持Android、iOS,还支持Windows、Linux等操作系统。Flutter的性能非常高,拥有120fps的刷新率。那么flutter是如何实现在不同平台上高性能绘制图形图像的呢?首先我们分析下Flutter App和原生Android App、原生iOS

大灰狼的小绵羊哥哥的博客 5821

图机器学习(7)——图神经网络 (Graph Neural Network, GNN)

图神经网络 (Graph Neural Network, GNN) 是一类专门处理图结构数据的深度学习方法。这类方法也被称为几何深度学习 (geometric deep learning),在社交网络分析、计算机图形学等众多领域正受到日益广泛的关注。在本节中,我们介绍了 GNN 的核心原理,将卷积等经典深度学习范式拓展至非欧几里得图空间,实现了局部结构与全局特征的层次化提取。

盼小辉丶的博客 1万+

解析 Flutter 渲染引擎:图层渲染与合成的底层原理

Flutter 渲染引擎是其高性能跨平台框架的核心,它通过图层渲染(Layer Rendering)和合成(Compositing)实现高效 UI 绘制。下面我将逐步解析其底层原理,从基础概念到具体机制,确保内容基于 Flutter 官方文档和实际实现(如 Skia 图形库),以帮助您深入理解。Flutter 渲染引擎的目标是将 Widget 树转换为屏幕像素,过程分为三个阶段:整个流程由 GPU 加速,确保 60fps 以上的流畅性。关键组件包括:图层(Layer)是渲染的基本单位,每个 Layer 代表

2501_93892472的博客 816

整流桥选型参数,结构原理,工艺与注意问题总结

整流桥(Rectifier Bridge)是一种电子元件,它的主要作用是将交流电(AC)转换为直流电(DC)。这种转换在许多电子设备中都是必要的,因为大多数电子元件和电路都需要直流电源来工作。本文对整流桥的工作原理,结构特点,工艺流程,选型参数及设计注意事项进行总结。

fydar的博客 2212

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

深入理解flutter_percent_indicator源码:从绘制原理到性能优化

flutter_percent_indicator是一个功能强大的Flutter进度指示器库,提供了圆形和线性两种进度展示方式。本文将从源码角度解析其绘制原理、核心功能实现及性能优化技巧,帮助开发者深入理解这个库的内部机制。 ## 核心组件架构 该库主要包含两个核心组件: - **CircularPercentIndicator**:圆形进度指示器,定义在[lib/circular_perc

gitblog_00391的博客 379

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

flutter自定义View(CustomPainter) 之 canvas的方法总结

前有大佬分享了用CustomPaint画一个自定义的CircleProgressBar的文章, 今天我分享一波自定义View(CustomPaint)的一些基础知识 画布canvas 画布是一个矩形区域,我们可以控制其每一像素来绘制我们想要的内容 canvas 拥有多种绘制点、线、路径、矩形、圆形、以及添加图像的方法,结合这些方法我们可以绘制出千变万化的画面。 虽然,画布可以画这些东西,但是决定这...

weixin_33929309的博客 820

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

终极Flutter音频可视化指南:从原理到惊艳实践的完整教程

Flutter引擎作为跨平台应用开发的强大框架,不仅在UI渲染上表现出色,还提供了丰富的音频处理能力。音频可视化技术能够将抽象的声音转化为直观的视觉效果,为音乐类、播客类应用增添沉浸式体验。本文将带你深入探索Flutter音频可视化的实现原理,掌握从基础波形绘制到高级频谱动画的全过程,让你的应用瞬间提升专业质感! ## 🎵 Flutter音频可视化基础:核心概念与技术栈 音频可视化的本质是将

gitblog_00419的博客 423

FlutterUnit虚线绘制:dash_painter自定义绘制深度解析

在Flutter应用开发中,虚线绘制是一个常见但容易被忽视的需求。无论是时间轴的分割线、辅助网格线,还是装饰性边框,虚线都能为界面增添专业感和视觉层次。然而,Flutter框架本身并未提供原生的虚线绘制支持,这给开发者带来了一定的挑战。 FlutterUnit作为一款全面的Flutter学习应用,通过集成`dash_painter`包,优雅地解决了虚线绘制问题。本文将深入解析FlutterUni...

gitblog_00943的博客 883

深入探索Android布局优化(上)

以下是资料目录和内容部分截图里面包括详细的知识点讲解分析,带你一个星期入门Flutter。还有130个进阶学习项目实战视频教程,让你秒变大前端。《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!化!**由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)以下是资料目录和内容部分截图。

2401_84150043的博客 1112

FlutterUI(二)Canvas 与 Paint

Flutter自定义控件分为三大类: 组合控件,通过组合其他widget成为一个新的widget。 自绘控件,通过使用canvas与paint来完全绘制。 继承widget,使用RenderObject来绘制,但最终还是使用canvas来绘制。 本文重点 着重介绍自绘控件,因为所有的widget归根结底都是使用canvas和paint来绘制的,理解了二者,对于其他的widget原理有溯源的功效。 Canvas:画布 Paint:画笔 怎么做? 继承CustomPainter 重写paint

大灰狼的小绵羊哥哥的博客 1044

Harmony Flutter 跨平台开发实战:鸿蒙与音乐律动艺术、Voronoi 泰森多边形:空间分割的动态演化

给定平面上的 n 个点(称为站点或种子点)P = {p₁, p₂, …对于每个区域 V(pᵢ)其中 d(x, y) 表示两点间的欧几里得距离。关键概念概念定义说明📍站点种子点 pᵢVoronoi 区域的中心📐Voronoi 区域V(pᵢ)离该站点最近的点集📏Voronoi 边两区域边界到两站点等距的点⭐Voronoi 顶点多边交点到多个站点等距的点🔗Delaunay 三角剖分Voronoi 对偶连接相邻站点的三角形Voronoi 图示意:│╲ │ ╱││ ╲ │ ╱ │。

2601_94959365的博客 674

学习Flutter从这开始(邂逅Flutter)

邂逅Flutter 一. 认识Flutter 1.1. 什么是Flutter 先看看官方的解释: Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile[1], web[2], and desktop[3] from a single codebase. 简...

EmotionComputer 738

任意的形状的Shape

待写

252

58、Flutter核心原理--绘制原理及Layer

Flutter 绘制原理 Flutter中和绘制相关的对象有三个,分别是Canvas、Layer 和 Scene: Canvas:封装了Flutter Skia各种绘制指令,比如画线、画圆、画矩形等指令。 Layer:分为容器类和绘制类两种;暂时可以理解为是绘制产物的载体,比如调用 Canvas 的绘制 API 后,相应的绘制产物被保存在 PictureLayer.picture 对象中。 Scene:屏幕上将要要显示的元素。在上屏前,我们需要将Layer中保存的绘制产物关联到 Scene 上。 F

wywinstonwy的专栏 1万+
上一篇: 【Flutter】时间轴高度自适应最佳实践
下一篇: 【Flutter】一文搞懂异步编程
Tech Ranger
博客等级 码龄10年 115粉丝 101原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值