2

I've been learning about painting custom shapes in Flutter. Canvas has a method called drawOval(). An oval is not mathematically defined like an ellipse is, so not all ovals are ellipses. I assume that "oval" is an ellipse in this case, but I wanted to confirm that by looking at the source code.

Flutter uses Skia to draw things and I found this class, but I still couldn't understand how the oval is drawn under the hook in Skia. (I know how to draw an oval in Flutter.)

Is the Flutter/Skia oval an ellipse? Where is it actually computed and drawn in the source code?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

1 Answers1

0

Canvas.drawOval() method as the name implies, can draw an oval. A circle is an oval - one with equal axes. An ellipse is also an oval, one that could be a circle that has been stretched. To sum it up, drawOval can draw a circle and ellipse.

Depending on the Rect defined on drawOval(), the oval drawn on canvas can either be a circle or an ellipse.

Here's a sample that you can try out. OvalPainter demonstrates drawing of a circle and an ellipse on a Canvas.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: CustomPaint(
        painter: OvalPainter(),
      ),
    );
  }
}

class OvalPainter extends CustomPainter {
  final paintConfig = Paint()
    ..style = PaintingStyle.fill
    ..color = Colors.red;

  @override
  void paint(Canvas canvas, Size size) {
    // Circle
    canvas.drawOval(const Rect.fromLTRB(200, 200, 10, 10), paintConfig);

    // Ellipse
    // canvas.drawOval(const Rect.fromLTRB(100, 200, 10, 10), paintConfig);

    // Ellipse
    // canvas.drawOval(const Rect.fromLTWH(10, 10, 100, 200), paintConfig);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
Omatt
  • 8,564
  • 2
  • 42
  • 144