Search code examples
dartflutterflutter-layout

How do I crop a widget, or cut out a square portion of a widget of that particular size?


I want to crop a CameraPreview widget, so that I only get the exact size and position where I want to cut it.

Currently I am able to clip it using ClipRect, but i get this black area around where widget was clipped out which I want to remove ( see my replacement for a good graphic below )

Lets say we have a widget like this

 --------------                       
|88888888888888|                               
|88888888888888|                   
|88888888888888|                     
|88888888888888|                      
|88888888888888|                     
|88888888888888|                     
 --------------  

I need to crop the widget, (not clip)

 --------------                       
|              |                               
|              |                    
|         888  |                      -----
|         888  |                     | 888 | 
|         888  |                     | 888 | 
|              |                     | 888 |
 --------------                       -----
     CLIPPING                        CROPPING

Can anyone help me with cropping a widget?


Solution

  • Nevermind i managed to solve it on my own, It felt like flutter framework works in mysterious ways until i figured this out

    return Container( // just a parent
          child: Align( // important
            alignment: Alignment.center,
            child: Container( // just a parent
              width: some_width,  
              height: some_height,  
              child: SizedBox(
                width: width,  // final width of cropped portion
                height: width,  // final height of cropped portion
                child: OverflowBox(
                  alignment: Alignment(-1,-1), // gives you top left portion of the size above, (1,1) gives bottom right, right direction is positive x, downward direction is positive y, see about Alignment on flutter docs for more details 
                  maxWidth: double.infinity,
                  maxHeight: double.infinity,
                  child: Container(
                    width: width,
                    height: width,
                    child: ClipRect(
                      clipper: RectClipper(i, width / 4),// this is a custom clipper i made of type CustomClipper<Rect>
                      child: CameraPreview(controller),
                    ),
                  ),
                ),
              ),
            ),
          ),
        );