user9469335
user9469335

Reputation: 192

How to draw a cross in Flutter canvas?

I am new to Flutter - Canvas. I need to draw a cross, just like below. I thought of drawing 2 lines and placing them in a stack with on line rotated by 90 degrees but I am not sure about it. Can anyone help me with this?

this

Upvotes: 2

Views: 2175

Answers (2)

Zihan
Zihan

Reputation: 942

The above solution will provide you with 2 lines of 1-pixel width. If anyone wondering how to increase the width of the lines then the below code will help you


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SamplePage(),
    );
  }
}

const kCanvasSize = 300.0;

class SamplePage extends StatefulWidget {
  const SamplePage({Key? key}) : super(key: key);

  @override
  _SamplePageState createState() => _SamplePageState();
}

class _SamplePageState extends State<SamplePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          decoration: BoxDecoration(
              border: Border.all(color: Colors.greenAccent, width: 2)),
          width: kCanvasSize,
          height: kCanvasSize,
          child: CustomPaint(
            painter: CrossDrawPaint(),
            child: Container(),
          ),
        ),
      ),
    );
  }
}

class CrossDrawPaint extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint crossBrush = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.stroke
      ..strokeWidth = 12;
    canvas.drawLine(const Offset(50, 50),
        Offset(size.width - 50, size.height - 50), crossBrush);
    canvas.drawLine(
        Offset(size.width - 50, 50), Offset(50, size.height - 50), crossBrush);
  }

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

Hope this simple app helps the future user

Upvotes: 2

OMANSAK
OMANSAK

Reputation: 1332

void paint(Canvas canvas, Size size) { 
    final paint = Paint(); 
    paint.color = Colors.red; 
    canvas.drawLine(new Offset(0, 0), new Offset(size.width, size.height), paint);
    canvas.drawLine(new Offset(size.width, 0), new Offset(0, size.height), paint); 
}

Upvotes: 4

Related Questions