Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a custom shape in flutter

Tags:

flutter

dart

I just want to draw a spin wheel. How to draw a circle like this? enter image description here

like image 797
Kavin-K Avatar asked Jan 19 '19 18:01

Kavin-K


People also ask

How do you make custom paint in Flutter?

Custom Painter is : A widget that provides a canvas on which to draw during the paint phase. :To paint in Flutter you can use the CustomPaint widget which basically takes size of its parent if not given the child . The CustomPainter subclass overrides two methods: paint() and shouldRepaint() .


1 Answers

A solution is to implement a custom painter (CustomPainter) then use the arcTo method to draw each part of the wheel.

You can then set the color using canvas.drawPath.

Finally use it wherever you want using a CustomPaint widget :

Full working example :

import 'dart:math';
import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeState();
  }
}

class WheelPainter extends CustomPainter {
  Path getWheelPath(double wheelSize, double fromRadius, double toRadius) {
    return new Path()
      ..moveTo(wheelSize, wheelSize)
      ..arcTo(Rect.fromCircle(radius: wheelSize, center: Offset(wheelSize, wheelSize)), fromRadius, toRadius, false)
      ..close();
  }

  Paint getColoredPaint(Color color) {
    Paint paint = Paint();
    paint.color = color;
    return paint;
  }

  @override
  void paint(Canvas canvas, Size size) {
    double wheelSize = 100;
    double nbElem = 6;
    double radius = (2 * pi) / nbElem;

    canvas.drawPath(getWheelPath(wheelSize, 0, radius), getColoredPaint(Colors.red));
    canvas.drawPath(getWheelPath(wheelSize, radius, radius), getColoredPaint(Colors.purple));
    canvas.drawPath(getWheelPath(wheelSize, radius * 2, radius), getColoredPaint(Colors.blue));
    canvas.drawPath(getWheelPath(wheelSize, radius * 3, radius), getColoredPaint(Colors.green));
    canvas.drawPath(getWheelPath(wheelSize, radius * 4, radius), getColoredPaint(Colors.yellow));
    canvas.drawPath(getWheelPath(wheelSize, radius * 5, radius), getColoredPaint(Colors.orange));
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return oldDelegate != this;
  }
}

class _HomeState extends State<Home> {
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('Wheel test'),
        leading: new Icon(Icons.insert_emoticon),
      ),
      backgroundColor: Colors.white,
      body: CustomPaint(
        child: Container(
          height: 300.0,
        ),
        painter: WheelPainter(),
      ),
    );
    //]));
  }
}

Result :

Colored wheel screenshot

If you attemp to draw pie charts you better go with a Charting library.

like image 113
Yann39 Avatar answered Sep 28 '22 02:09

Yann39