import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';

// class GridClipPaint extends StatelessWidget {
//   const GridClipPaint(
//     this.left,
//     this.top,
//     this.right,
//     this.bottom, {
//     Key key,
//   }) : super(key: key);
//
//   // ui.Image image;
//   final double left;
//   final double top;
//   final double right;
//   final double bottom;
//
//   @override
//   Widget build(BuildContext context) {
//     ui.Image image;
//     return Container(
//       color: Colors.transparent,
//       alignment: Alignment.center,
//       child: CustomPaint(
//         // 使用CustomPaint 背景画板
//         painter: ClipPainter(image),
//       ),
//     );
//   }
// }

class GridClipPaint extends StatefulWidget {
  const GridClipPaint(this.image, this.left, this.top, this.right, this.bottom,
      {Key key})
      : super(key: key);
  final ui.Image image;
  final double left;
  final double top;
  final double right;
  final double bottom;

  @override
  State<GridClipPaint> createState() => _GridClipPaintState();
}

class _GridClipPaintState extends State<GridClipPaint> {
  ui.Image image;

  @override
  void initState() async {
    // TODO: implement initState
    // final appDataDirectory = await getApplicationDocumentsDirectory();
    // File file = File(join(appDataDirectory.path, 'rotate_image'));
    super.initState();
  }

  Future<ui.Image> imageLoader() {
    ImageStream imageStream = const AssetImage("assets/images/arrow.png")
        .resolve(ImageConfiguration(size: Size(700, 700)));
    Completer<ui.Image> imageCompleter = Completer<ui.Image>();

    void imageListener(ImageInfo info, bool synchronousCall) {
      ui.Image image = info.image;
      imageCompleter.complete(image);
      imageStream.removeListener(ImageStreamListener(imageListener));
    }

    imageStream.addListener(ImageStreamListener(imageListener));
    return imageCompleter.future;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.transparent,
      alignment: Alignment.center,
      child: CustomPaint(
        // 使用CustomPaint 背景画板
        painter: ClipPainter(image),
      ),
    );
  }
}

class ClipPainter extends CustomPainter {
  final ui.Image image;
  final double left;
  final double top;
  final double right;
  final double bottom;

  ClipPainter(this.image,
      {this.left = 0.3, this.top = 0.3, this.right = 0.6, this.bottom = 0.6});

  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    Paint paint = Paint();
    canvas.drawImageRect(
        image,
        Rect.fromLTRB(image.width * left, image.height * top,
            image.width * right, image.height * bottom),
        Rect.fromLTWH(0, 0, size.width, size.height),
        paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return false;
  }
}
