如何在Flutter中通过ClipPath获取剪辑部分

时间:2018-11-24 09:08:04

标签: canvas flutter

我要剪切图像的一部分,然后使用Slider移动剪辑。但是我发现片段大小与图像相同是很奇怪的。我怎么只能得到剪辑?

屏幕快照中的

,上面是原始图像,下面是该图像的剪辑,但是它们的大小是相同的。我想获得圆形部分。

屏幕截图:

image

这是代码:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Startup Name Generator',
      home: Test2(),
    );
  }
}

class Test2 extends StatefulWidget {
  @override
  _Test2State createState() => _Test2State();
}

class _Test2State extends State<Test2> {
  final String imageFile = "images/snow.jpg";

  double dy = 100;
  double size = 20;
  double blockCenterX = 250;
  double width = 300;
  double height = 300;
  Widget blockWidget;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _changeBlockImage();
  }

  @override
  Widget build(BuildContext context) {
    print("screen width: $width");
    return Scaffold(
      appBar: AppBar(
        title: Text("ClipPath test"),
      ),
      body: Column(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
        Container(
          width: width,
          height: height,
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage(imageFile), fit: BoxFit.fill)),
        ),
        Container(
          color: Colors.yellow,
          child: blockWidget,
        )
      ]),
    );
}

  _changeBlockImage() {
    setState(() {
      blockWidget = _getBlock();
    });
  }

  Widget _getBlock() {
    _resetBlockOffset();
    return Stack(children: [
      ClipPath(
        clipper: BlockClipper(
          origin: Offset(blockCenterX, dy),
          blockSize: Size(size, size),
        ),
        child: Container(
          width: width,
          height: height,
          decoration: BoxDecoration(
              image: DecorationImage(
            image: AssetImage(imageFile),
            fit: BoxFit.fill,
          )),
        ),
      ),
      CustomPaint(
        painter: BorderPaint(
          origin: Offset(blockCenterX, dy),
          radius: size,
        ),
        child: SizedBox(
          width: width,
          height: height,
        ),
      )
    ]);
  }
}

class BorderPaint extends CustomPainter {
  Offset origin;
  double radius;
  BorderPaint({this.origin, this.radius});

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.blue
      ..strokeWidth = 2
      ..style = PaintingStyle.stroke;

    canvas.drawCircle(origin, radius, paint);
  }

  @override
  bool shouldRepaint(BorderPaint old) {
    return true;
  }
}

0 个答案:

没有答案