You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Flutter中如何为图片添加贴合形状的自定义阴影?

Fix: Get Image-Shaped Shadow Instead of Square BoxShadow in Flutter

Hey there! I get exactly what you're dealing with—BoxShadow sticks to the container's square bounds, not the actual shape of your image, which is super frustrating when you need a shadow that wraps around the image's contour. Let's break down the solutions based on your image type:

1. For Rounded Rectangular Images

If your image has rounded corners, the fix is simple: just match the borderRadius of your BoxDecoration to the rounded corners of your image. This clips the container (and its shadow) to the same rounded shape as the image:

Container(
  decoration: BoxDecoration(
    // Adjust this value to match your image's corner radius
    borderRadius: BorderRadius.circular(12),
    image: DecorationImage(
      image: AssetImage('images/image 2.png'),
      fit: BoxFit.cover, // Ensure the image fills the container properly
    ),
    boxShadow: [
      BoxShadow(
        color: Color.fromRGBO(0, 0, 0, 0.25),
        offset: Offset(0, 4),
        blurRadius: 4,
      ),
    ],
  ),
)

2. For Irregularly Shaped Images (Transparent PNGs)

If your image is an irregular shape (like a logo with transparent background), BoxShadow won't cut it—you need to generate a shadow that follows the image's alpha channel. Use a Stack to layer a blurred, darkened version of the image underneath the original:

Stack(
  alignment: Alignment.center,
  children: [
    // The shadow layer: blurred and darkened version of your image
    Transform.translate(
      offset: Offset(0, 4), // Match your original shadow offset
      child: ImageFiltered(
        imageFilter: ImageFilter.blur(sigmaX: 4, sigmaY: 4), // Match your blur radius
        child: Image.asset(
          'images/image 2.png',
          color: Color.fromRGBO(0, 0, 0, 0.25), // Match your shadow color
          colorBlendMode: BlendMode.multiply,
        ),
      ),
    ),
    // Your original image on top
    Image.asset('images/image 2.png'),
  ],
)

Why This Works

  • The ImageFiltered widget blurs the shadow layer to match your original blur intensity.
  • The color and colorBlendMode darken the image to create the shadow effect, which only appears where the image has pixels (thanks to the transparent background).
  • Tweak sigmaX/sigmaY to adjust blur strength, and adjust the Offset in Transform.translate to control shadow position.

Quick Note

Make sure your image has a transparent background (PNG) for the irregular shape solution to work—JPGs with solid backgrounds will still show a square shadow.

内容的提问来源于stack exchange,提问作者Tugba Ozkan

火山引擎 最新活动