Use image as background of custom shape Card/Material widget

402

Solution 1

For Android create a CustomClipper class:

class ImageContinuousClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    return ContinuousRectangleBorder(borderRadius: BorderRadius.circular(200 * 0.625))
        .getOuterPath(Rect.fromLTWH(0, 0, size.width, size.height));
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}

In general, you can do this:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 200,
          child: AspectRatio(
            aspectRatio: 1,
            child: Card(
              shape: ContinuousRectangleBorder(
                borderRadius: BorderRadius.circular(200 * 0.625),
              ),
              child:Image.network(
                  'https://images.pexels.com/photos/2853198/pexels-photo-2853198.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500',
                  fit: BoxFit.cover),
            ),
          ),
        ),
      ),
    );
  }
}

Solution 2

try this :

 Material(
  shape: ContinuousRectangleBorder(
    borderRadius: BorderRadius.circular(50),
  ),
  elevation: 4,
  color: theme.primaryColor,
  child: image,
  borderOnForeground: true,
  clipBehavior: Clip.antiAliasWithSaveLayer,
)
Share:
402
Hamed Hamedi
Author by

Hamed Hamedi

Updated on December 22, 2022

Comments

  • Hamed Hamedi
    Hamed Hamedi over 1 year

    There is a ContinuousRectangleBorder paint which I can pass to the shape parameter of Card or Material widget.

    Material(
      shape: ContinuousRectangleBorder(
        borderRadius: BorderRadius.circular(50),
      ),
      elevation: 4,
      color: theme.primaryColor,
      child: image,
      borderOnForeground: true,
    )
    

    But in android if I pass an image to the widget, the image won't clip as the parent. What is the best way to crop image with the identical shape?