将图像的一部分绘制到小部件上

Mik*_*ler 5 dart flutter

我正在尝试将精灵绘制到 CustomPaint 小部件上。该精灵来自网格中包含多个精灵的图像,因此我需要能够指定源矩形(最好是与小部件大小匹配的目标矩形)。

Mik*_*ler 8

我使用 canvas.drawAtlas 解决了这个问题:

import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'dart:ui' as ui;

class SquarePainter extends CustomPainter {
  final ui.Image theImage;
  SquarePainter({this.theImage});
  @override
  void paint(Canvas canvas, Size size) {

    canvas.drawAtlas(
        theImage,
        [
          /* Identity transform */
          RSTransform.fromComponents(
              rotation: 0.0,
              scale: 1.0,
              anchorX: 0.0,
              anchorY: 0.0,
              translateX: 0.0,
              translateY: 0.0)
        ],
        [
            /* A 5x5 source rectangle within the image at position (10, 10) */
            Rect.fromLTWH(10.0, 10.0, 5.0, 5.0)
        ],
        [/* No need for colors */],
        BlendMode.src,
        null /* No need for cullRect */,
        Paint());
  }

  @override
  bool shouldRepaint(SquarePainter oldDelegate) => false;
  @override
  bool shouldRebuildSemantics(SquarePainter oldDelegate) => false;
}
Run Code Online (Sandbox Code Playgroud)