Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you "center crop" a Widget in Flutter?

Tags:

flutter

I have a VideoPlayer widget that needs to be fullscreen and also fit the aspect ratio of the source video. In order to achieve that, I'll need to chop off either the top/bottom or the left/right of the video.

I had hoped the following might achieve this, but I think I must be using FittedBox incorrectly as it causes my VideoPlayer to disappear:

final Size size = controller.value.size;
return new FittedBox(
  fit: BoxFit.cover,
  child: new AspectRatio(
    aspectRatio: size.width / size.height,
    child: new VideoPlayer(controller)
  ),
);

Can anyone help me solve this? 🙏

like image 650
Bradley Campbell Avatar asked Mar 26 '18 00:03

Bradley Campbell


People also ask

How do you change the widget position in flutter?

Here's how you do it:Step 1: Wrap the Stack's child widget inside the Position widget. Step 2: Inside the Position widget, add the top , right , bottom , left property and give it a value. For example, setting top:15 and right:0 will position a widget on the top right of your screen with 15 px space from the top.

How do you crop a circle in flutter?

Draw circle in canvas using canvas. Call endRecording() on the PictureRecorder to get a Picture. Call toImage() on the Picture. Convert image toByteData() . Save image locally using getApplicationDocumentsDirectory() ,only if you want to save.


2 Answers

Finally solved it. There were a few missing pieces:

  1. I needed an OverflowBox with no restrictions so that my child could grow as large as needed.
  2. I needed the child of FittedBox to actually enforce a size to stop the layout system from crashing.
  3. Now that my widget will paint outside of its bounds, we also want to put a ClipRect in there to stop this from happening.
final Size size = controller.value.size;
return new ClipRect(
  child: new OverflowBox(
    maxWidth: double.infinity,
    maxHeight: double.infinity,
    alignment: Alignment.center,
    child: new FittedBox(
      fit: BoxFit.cover,
      alignment: Alignment.center,
      child: new Container(
        width: size.width,
        height: size.height,
        child: new VideoPlayer(controller)
      )
    )
  )
);
like image 176
Bradley Campbell Avatar answered Oct 14 '22 15:10

Bradley Campbell


Starting with the above solution I came up with this:

final Size size = _controller.value.size;
return Container(
  color: Colors.lightBlue,
  width: MediaQuery.of(context).size.width,
  height: MediaQuery.of(context).size.width,
  child: FittedBox(
           alignment: Alignment.center,
       fit: BoxFit.fitWidth,
       child: Container(
         width: size.width,
         height: size.height,
         child: VideoPlayer(_controller))),
      ),
)

The inner Container provides the size for the Texture inside the VideoPlayer.

like image 41
Danny Thuering Avatar answered Oct 14 '22 16:10

Danny Thuering