如何剪辑在画布外绘制的对象?下面,黑色方块代表画布的边界。我不想绘制圆的左半部分,因为它位于画布之外:
这是一个简单的示例,但我正在画布内绘制 PNG 和 SVG,并对其应用了各种转换,并且我需要一个解决方案来剪辑在画布外绘制的部分。
这是上面的代码:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Container(
width: 200,
height: 200,
child: CustomPaint(
child: Container(),
painter: CanvasPainter(),
),
)),
),
);
}
}
class CanvasPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
canvas.drawRect(
Rect.fromLTWH(0, 0, size.width, size.height),
Paint()
..style = PaintingStyle.stroke
..color = Colors.black);
canvas.save();
canvas.translate(0.0, 100.0);
canvas.drawCircle(Offset(0, 0), 50.0, Paint()..color = Colors.blue);
canvas.restore();
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
Run Code Online (Sandbox Code Playgroud)
你需要添加
canvas.clipRect(rect);
这样你的代码是这样的:
void paint(Canvas canvas, Size size) {
final rect = Rect.fromLTWH(0, 0, size.width, size.height);
canvas.drawRect(
rect,
Paint()
..style = PaintingStyle.stroke
..color = Colors.black);
canvas.clipRect(rect);
canvas.save();
canvas.translate(0.0, 100.0);
canvas.drawCircle(Offset(0, 0), 50.0, Paint()..color = Colors.blue);
canvas.restore();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2018 次 |
| 最近记录: |