首页 > 解决方案 > 如何在容器中心垂直和水平地画一条线?

问题描述

我想标记屏幕的确切中心。我将如何绘制两条线,一条垂直居中,一条水平居中?

标签: flutter

解决方案


使用以下使用自定义painter的代码,您可以通过更改AKCustomPainter类中Paint类的color属性来改变线条的颜色

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

void main() => runApp(Demo());

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SnackBar Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Demo'),
        ),
        body: Container(
              child: CustomPaint(
                size: Size(800,500), //You can Replace this with your desired WIDTH and HEIGHT
                painter: AKCustomPainter(),
)),
      ),
    );
  }
}
class AKCustomPainter extends CustomPainter{
  
  @override
  void paint(Canvas canvas, Size size) {
    
    
  // Vertical line
  Paint paint_0 = new Paint()
      ..color = Color.fromARGB(255, 33, 150, 243)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.34;
     
         
    Path path_0 = Path();
    path_0.moveTo(size.width*0.50,0);
    path_0.lineTo(size.width*0.50,size.height);

    canvas.drawPath(path_0, paint_0);
  
  
  // Horizontal line
  Paint paint_1 = new Paint()
      ..color = Color.fromARGB(255, 33, 150, 243)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.34;
     
         
    Path path_1 = Path();
    path_1.moveTo(0,size.height*0.50);
    path_1.lineTo(size.width,size.height*0.50);

    canvas.drawPath(path_1, paint_1);
  
    
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
  
}

推荐阅读