Skip to content

Instantly share code, notes, and snippets.

@410063005
Created December 27, 2019 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 410063005/cb832229e3e0cf4db4af1eecde1119c4 to your computer and use it in GitHub Desktop.
Save 410063005/cb832229e3e0cf4db4af1eecde1119c4 to your computer and use it in GitHub Desktop.
RenderObject 示例
class CircleTextWidget extends SingleChildRenderObjectWidget {
CircleTextWidget({
Key key,
Widget child,
}) : super(key: key, child: child);
@override
RenderCircleText createRenderObject(BuildContext context) =>
RenderCircleText();
}
class RenderCircleText extends RenderProxyBox {
RenderCircleText({RenderBox child}) : super(child);
@override
void paint(PaintingContext context, Offset offset) {
super.paint(context, offset);
// 父节点的宽高分别是 200, 200
// dx, dy 分别是 100, 100
double dx = constraints.constrainWidth() / 2;
double dy = constraints.constrainHeight() / 2;
// 中心点坐标
Offset center = offset.translate(size.width / 2, size.height / 2);
// 左上角坐标
Offset topLeft = center.translate(-dx, -dy);
// 右上角坐标
Offset topRight = center.translate(dx, -dy);
// 左下角坐标
Offset bottomLeft = center.translate(-dx, dy);
// 右下角坐标
Offset bottomRight = center.translate(dx, dy);
Paint paint = Paint()..color = Colors.amber;
// 蓝色矩形中心点
context.canvas.drawRect(
Rect.fromCenter(center: center, width: 18, height: 18),
paint..color = Colors.blue);
// 四角的圆形点
context.canvas.drawCircle(topLeft, 10, paint..color = Colors.red);
context.canvas.drawCircle(topRight, 10, paint..color = Colors.yellow);
context.canvas.drawCircle(bottomLeft, 10, paint..color = Colors.orange);
context.canvas.drawCircle(bottomRight, 10, paint..color = Colors.green);
if (child != null) {
context.paintChild(child, offset);
}
}
}
void main() {
runApp(Center(
// 运行效果见 https://www.sunmoonblog.com/images/15774370864830.jpg
child: SizedBox(
width: 200,
height: 200,
child: Center(
child: CircleTextWidget(
child: Text(
'hello, renderBox',
textDirection: TextDirection.ltr,
),
),
))));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment