Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove exceeding shape in CustomPaint?

Tags:

flutter

I am trying to draw a half circle in a rectangle in flutter like this.

enter image description here

But in my code, the Circle exceeds the white rectangle onto the black background like this

enter image description here

What changes should I make to the code to get the result like the first pic?

My code:-

import 'package:flutter/material.dart';

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
          child: Scaffold(  
            backgroundColor: Colors.black,
            body: Center(  
              child: Container(  
                height: 200,
                width: 200,

                color: Colors.white,
                child: CustomPaint(
                  painter: Circ(),
                    child: Column(  
                    children: <Widget>[

                    ],
                  ),
                ),
              
              ),
            ),
          )
    ),
    );
  }
}

class Circ extends CustomPainter{
  
  @override 
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    
    
    
    paint.color = Colors.blue.withOpacity(0.2);
    
    var center1 = Offset(200,100);
    
    canvas.drawCircle(center1,100, paint); 

    
  }

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


like image 547
Shahbaz Avatar asked Oct 25 '25 02:10

Shahbaz


1 Answers

It seems your circle is drawn outside the area you want to confine your painting to.

If you want to paint only in a specified part of the canvas, that is called "clipping".

Add the clipping:

canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height));

canvas.drawCircle(center1, 100, paint); 

This way your circle will not be painted outside the given size.

like image 81
nvoigt Avatar answered Oct 26 '25 19:10

nvoigt