0

Im using MLKit and custom painter to dynamically draw on screen when it detects something, however I would like to be able to show an image within that polygon resized to fit within the shape.

It seems there is UI.Image which can be used along with the canvass function drawImage, but that doesn't seem to support polygons.

Any help or suggestions would be appreciated.

    class MyPainter extends CustomPainter {
  final Offset firstPoint;
  final Offset secondPoint;
  final Offset thirdPoint;
  final Offset fourthPoint;

  MyPainter(
      this.firstPoint, this.secondPoint, this.thirdPoint, this.fourthPoint);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..color = Color(0xff638965)
      ..style = PaintingStyle.fill;

    canvas.drawPath(
        Path()
          ..addPolygon([
            firstPoint,
            secondPoint,
            thirdPoint,
            fourthPoint,
          ], true),
        paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}
Yonkee
  • 1,781
  • 3
  • 31
  • 56
  • 1
    call `clipPath` before drawing your inage – pskink May 14 '23 at 06:14
  • @pskink Thanks for the quick response. I created a customerClipper using the same Path object as the CustomPainter and wrapped the image container in a ClipPath. Does the trick. Cheers mate. – Yonkee May 14 '23 at 06:40
  • if you want to draw clipped image inside your `MyPainter` just do `canvas.clipPath` followed by `canvas.drawImage` - no need for `ClipPath` – pskink May 14 '23 at 07:09
  • @pskink That works also, thanks. However the image still isn't resized to the polygon. It seems to be fixed size in the corner of the screen and the image is revealed by the polygon rather than filled the entire time. Also the Offset is off which is proably related. – Yonkee May 14 '23 at 22:02
  • use `Canvas.drawImageRect` then (or even better [paintImage](https://api.flutter.dev/flutter/painting/paintImage.html) top level function as it scales the image automatically) – pskink May 15 '23 at 05:43

0 Answers0