Flutter: center overflowed image in Stack

Viewed 881

I have an image and I want to place it in the Stack widget which has smaller size than initial image.

Also I need to center this image inside smaller widget.

enter image description here

For now I found one approach which allows just to set overflowing image size inside smaller parent widget.

Container(
  width: 50.0,
  height: 50.0,
  child: Stack(
    children: [
      Positioned(
        width: 150.0,
        height: 150.0,
        child: Image.asset('assets/images/example.jpg'),
      )
    ]
  )
)

But in this case I have to center image by setting top and left offsets manually because any alignment doesn't work in this case.

Container(
  width: 50.0,
  height: 50.0,
  child: Stack(
    children: [
      Positioned(
        width: 150.0,
        height: 150.0,
        child: Align(
          alignment: Alignment.center,
          child: Image.asset('assets/images/example.jpg'),
        )
      )
    ]
  )
)

enter image description here

If I use Positioned.fill - I can't then set the size of overflowing widget space, so that it doesn't work too.

If I increase the scale of an image it just makes initial image smaller rather than increase size of an image and crop overflowed space.

enter image description here

I need to make image overflowed and centered automatically by some alignment property.

Can't find solution for this issue yet.

I don't know how to do it in Flutter but with CSS it is very easy:

div {
  width: 100px;
  height: 100px;
  background: url('https://img.icons8.com/clouds/2x/sun.png') no-repeat;
  background-size: 200px 200px;
  background-position: center;
  border: 1px solid black;
  border-radius: 5px;
}
<div>

</div>

1 Answers

If I understood you correctly the same effect as per your CSS could be achieved by Centering the Container and setting the Image BoxFit to none. Please see the code below :

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Demo'),
      ),
      body: Center(
        child: Container(
          width: 100.0,
          height: 100.0,
          child: Image.network('https://img.icons8.com/clouds/2x/sun.png',
              fit: BoxFit.none),
        ),
      ),
    );
  }
}
Related