[英]How to draw a rectangle using 4 coordinates?
I have a use case in which I've to draw a rectangle using the 4 coordinates.我有一个用例,我必须使用 4 个坐标绘制一个矩形。 I don't want to use drawLine() as later I need a GestureDetector on the rectangle.
我不想使用 drawLine(),因为稍后我需要在矩形上使用 GestureDetector。 How can I draw using drawRect()?
如何使用 drawRect() 进行绘制?
canvas.drawLine(
new Offset(rectLeft, rectBottom - lineWidth / 2),
new Offset(rectRight, rectBottom - lineWidth / 2),
rectPaint
); // bottom
canvas.drawLine(
new Offset(rectLeft, rectTop + lineWidth / 2),
new Offset(rectRight, rectTop + lineWidth / 2),
rectPaint
); // top
canvas.drawLine(
new Offset(rectLeft + lineWidth / 2, rectBottom),
new Offset(rectLeft + lineWidth / 2, rectTop),
rectPaint
); //left
canvas.drawLine(
new Offset(rectRight - lineWidth / 2, rectBottom),
new Offset(rectRight - lineWidth / 2, rectTop),
rectPaint
); //right
For this use case, Dart provides the Rect
class : 对于这个用例, Dart提供了
Rect
类 :
canvas.drawRect(Rect.fromLTRB(left, top, right, bottom), paint);
In this case left
, top
, right
, and bottom
are the distances from origin as described here . 在这种情况下,
left
, top
, right
和bottom
是距离原点的距离, 如此处所述 。
Alternatively, you can specify two Offset
's as described here : 或者,您可以指定两个
Offset
, 如下所述 :
canvas.drawRect(Rect.fromPoints(a, b), paint);
Or, you can also use the width
and height
of your Rect
: 或者,您也可以使用
Rect
的width
和height
:
canvas.drawRect(Rect.fromLTWH(left, top, width, height), paint);
There is also Rect.fromCircle
, however, this does not really apply to your use case. 还有
Rect.fromCircle
,但是,这并不适用于您的用例。
You need to create a CustomPainter您需要创建一个 CustomPainter
class YourRect extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
canvas.drawRect(
new Rect.fromLTRB(0.0, 0.0, 50.0, 50.0),
new Paint()..color = new Color(0xFF0099FF),
);
}
@override
bool shouldRepaint(YourRect oldDelegate) {
return false;
}
}
then use it like this:然后像这样使用它:
new GestureDetector(
onTap: () {
debugPrint("hello");
},
child: Container(
width: 50,
height: 50,
child: CustomPaint(
painter: (YourdrawRect()),
),
),
),
You can simply use create a polygon and use drawPath()
function of the canvas
您可以简单地使用创建多边形并使用
canvas
drawPath()
函数
canvas.drawPath(
Path()..addPolygon([
Offset(0, 0),
Offset(10, 0),
Offset(10, 10),
Offset(0, 10),
], true),
paint);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.