我想裁剪一个容器,如所附图像所示。 Image
谢谢。
答案 0 :(得分:0)
您可以使用 CustomPaint
绘制 round rectangle 和 ClipRect
仅将其一半渲染为“凹口”。
ClipRect(
child: Container(
color: Colors.lightBlueAccent,
height: 50,
width: 200,
child: CustomPaint(
painter: CustomPaintNotch(),
),
),
),
...
class CustomPaintNotch extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.green;
Offset center = Offset(size.width / 2, 0);
// As a notch, RRect will be drawn with offset
// With ClipRect used, paint outside the area won't be rendered
RRect roundRectangle = RRect.fromRectAndRadius(
Rect.fromCenter(center: center, width: 100.0, height: 40.0),
Radius.circular(20.0));
canvas.drawRRect(roundRectangle, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}
CustomPaintNotch 在 Container 小部件的顶部中心部分的边缘绘制一个圆角矩形。由于使用了 ClipRect,因此不会渲染超出区域的绘画。这将是矩形的缺口。
这是小部件呈现时的样子。
完整样本
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
// ClipRect was used so paint beyond ClipRect area won't be rendered
child: ClipRect(
child: Container(
color: Colors.lightBlueAccent,
height: 50,
width: 200,
child: CustomPaint(
painter: CustomPaintNotch(),
),
),
),
),
);
}
}
class CustomPaintNotch extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.green;
Offset center = Offset(size.width / 2, 0);
// As a notch, RRect will be drawn with offset
// With ClipRect used, paint outside the area won't be rendered
RRect roundRectangle = RRect.fromRectAndRadius(
Rect.fromCenter(center: center, width: 100.0, height: 40.0),
Radius.circular(20.0));
canvas.drawRRect(roundRectangle, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}