有时候总会遇到一些奇怪的需求,比如奇形怪状的Widget,今天主要搞一下如何实现这是Widget。
默认:子组件为正方形时裁剪成内贴圆形;为矩形时剪裁成内贴椭圆。
也可自定义Rect参数进行裁剪局域
ClipOval({Key? key, this.clipper, this.clipBehavior = Clip.antiAlias, Widget? child})
: assert(clipBehavior != null),
super(key: key, child: child);
ClipOval(
clipper: MyClipOval(),
child: Container(
width: 100,
height: 100,
color: Colors.red,
child: Center(
child: Text("ClipOval"),
),
),
)
class MyClipOval extends CustomClipper {
@override
bool shouldReclip(CustomClipper oldClipper) => false;
@override
Rect getClip(Size size) {
return Rect.fromLTRB(10.0, 10.0, size.width, size.height);
}
}
将子组件剪裁为圆角矩形
const ClipRRect({
Key? key,
this.borderRadius = BorderRadius.zero,
this.clipper,
this.clipBehavior = Clip.antiAlias,
Widget? child,
}) : assert(borderRadius != null || clipper != null),
assert(clipBehavior != null),
super(key: key, child: child);
ClipRRect(
borderRadius: BorderRadius.circular(20.dp),
child: Container(
width: 100,
height: 100,
color: Colors.red,
child: Center(
child: Text("ClipRRect"),
),
),
)
将子组件剪裁为给定的矩形大小
const ClipRect({ Key? key, this.clipper, this.clipBehavior = Clip.hardEdge, Widget? child })
: assert(clipBehavior != null),
super(key: key, child: child);
ClipRect(
clipBehavior: Clip.antiAlias,
child: Container(
width: 150,
height: 100,
color: Colors.red,
child: Image.network(
'https://img0.baidu.com/it/u=3436810468,4123553368&fm=26&fmt=auto',
fit: BoxFit.cover,
),
),
)
clipBehavior
参数:
none
:不裁剪hardEdge
:裁剪但不应用抗锯齿,裁剪速度比none
模式慢一点,但比其他方式快。antiAlias
:裁剪而且抗锯齿,以实现更平滑的外观。裁剪速度比antiAliasWithSaveLayer
快,比hardEdge
慢。antiAliasWithSaveLayer
:带有抗锯齿的剪辑,并在剪辑之后立即保存saveLayer
。自定义裁剪方式
const ClipPath({
Key? key,
this.clipper,
this.clipBehavior = Clip.antiAlias,
Widget? child,
}) : assert(clipBehavior != null),
super(key: key, child: child);
ClipPath(
clipper: MyClipper(),
child: Container(
width: 100,
height: 100,
color: Colors.red,
child: Center(
child: Text("ClipPath"),
),
),
)
class MyClipper extends CustomClipper {
@override
Path getClip(Size size) {
Path path = Path();
/// 起点
path.moveTo(10, 0);
/// 二阶贝塞尔曲线画弧,前两个为控制点坐标,后两点为终点坐标
path.quadraticBezierTo(10, 10, 0, 10);
/// 链接回到指定点
path.lineTo(0, 90);
path.quadraticBezierTo(10, 90, 10, 100);
path.lineTo(90, 100);
path.quadraticBezierTo(90, 90, 100, 90);
path.lineTo(100, 10);
path.quadraticBezierTo(90, 10, 90, 0);
return path;
}
@override
bool shouldReclip(CustomClipper oldClipper) => false;
}