如何剪輯在畫布外繪制的物件?在下面,黑色方塊代表畫布的邊界。我不希望繪制圓圈的左半部分,因為它在畫布之外:

這是一個簡單的示例,但我正在畫布內繪制 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;
}
uj5u.com熱心網友回復:
你需要添加
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();
}

uj5u.com熱心網友回復:
要防止小部件繪制超出其布局大小,請使用ClipRect 對其進行剪輯。對于圓形矩形,使用ClipRRect和ClipPath自定義形狀。
ClipRect(
child: Container(
width: 200,
height: 200,
child: CustomPaint(
child: Container(),
painter: CanvasPainter(),
),
),
)
您也可以在之前使用它CustomPaint。
我問了一個類似的問題,這個答案也解決了這種情況,我只是在這里重復一遍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/375664.html
