You need to enable JavaScript to run this app. Flutter中使用draw clipPath在同一页面绘制两个clip-path失败怎么办
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用draw clipPath在同一页面绘制两个clip-path失败怎么办

解决方案

核心踩坑点说明

  • 不要在CustomClipper中直接使用全局屏幕尺寸计算路径,必须基于当前传入的size参数(对应当前ClipPath组件的实际大小)生成路径,否则两个ClipPath的路径会互相干扰偏移
  • 两个ClipPath需要放在正确的布局容器中(如Column、Stack、Row),确保各自的约束范围独立,不会出现尺寸溢出重叠

完整可运行示例代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            // 第一个ClipPath效果
            ClipPath(
              clipper: FirstClipper(),
              child: Container(
                height: 220,
                width: double.infinity,
                color: Colors.blueAccent,
                child: const Center(child: Text("第一个裁剪区域", style: TextStyle(color: Colors.white, fontSize: 20))),
              ),
            ),
            // 第二个ClipPath效果
            ClipPath(
              clipper: SecondClipper(),
              child: Container(
                height: 220,
                width: double.infinity,
                color: Colors.orangeAccent,
                child: const Center(child: Text("第二个裁剪区域", style: TextStyle(color: Colors.white, fontSize: 20))),
              ),
            )
          ],
        ),
      ),
    );
  }
}

// 第一个自定义裁剪路径:底部波浪效果
class FirstClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();
    path.lineTo(0, size.height - 30);
    var firstControlPoint = Offset(size.width / 4, size.height);
    var firstEndPoint = Offset(size.width / 2, size.height - 30);
    path.quadraticBezierTo(firstControlPoint.dx, firstControlPoint.dy, firstEndPoint.dx, firstEndPoint.dy);
    var secondControlPoint = Offset(size.width * 3 /4, size.height - 60);
    var secondEndPoint = Offset(size.width, size.height - 30);
    path.quadraticBezierTo(secondControlPoint.dx, secondControlPoint.dy, secondEndPoint.dx, secondEndPoint.dy);
    path.lineTo(size.width, 0);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}

// 第二个自定义裁剪路径:上下斜角效果
class SecondClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();
    path.lineTo(0, 50);
    path.lineTo(0, size.height);
    path.lineTo(size.width, size.height - 50);
    path.lineTo(size.width, 0);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}

层叠场景适配

如果两个裁剪区域是层叠关系,只需将两个ClipPath放在Stack组件内,分别设置定位参数即可,CustomClipper的实现逻辑无需修改。

参考效果

示例图1
示例图2

内容的提问来源于stack exchange,提问作者user1595266

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 07:54:01