首页 > 解决方案 > Flutter:将盒子阴影添加到透明容器

问题描述

我正在尝试制作一个小部件来呈现此图像中显示的圆圈之一。它是一个带有盒子阴影的透明圆圈。圆圈应显示应用于父容器的任何颜色或背景图像。圆圈是透明的,但我看到的是一个黑盒阴影,而不是父级的背景颜色。有什么建议么?

这是我到目前为止所拥有的:

class TransParentCircle extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: new Center(
          child: new Container(
            decoration: new BoxDecoration(
              border: new Border.all(width: 1.0, color: Colors.black),
              shape: BoxShape.circle,
              color: Colors.transparent,
              boxShadow: <BoxShadow>[
                BoxShadow(
                  color: Colors.black,
                  offset: Offset(1.0, 6.0),
                  blurRadius: 40.0,
                ),
              ],
            ),
            padding: EdgeInsets.all(16.0),
          ),
        ),
        width: 320.0,
        height: 240.0,
        margin: EdgeInsets.only(bottom: 16.0));
  }
}

标签: dartflutter

解决方案


正如你在BoxShadow课堂上看到的那样,他们继承了toPaint()这样的方法:

Paint toPaint() {
  final Paint result = Paint()
    ..color = color
    ..maskFilter = MaskFilter.blur(BlurStyle.normal, blurSigma);
  assert(() {
    if (debugDisableShadows)
      result.maskFilter = null;
    return true;
  }());
  return result;
}

...BlurStyle.normal而不是BlurStyle.outer我们想要的。

让我们创建一个BoxShadow采用BlurStyleas 参数的自定义。

import 'package:flutter/material.dart';

class CustomBoxShadow extends BoxShadow {
  final BlurStyle blurStyle;

  const CustomBoxShadow({
    Color color = const Color(0xFF000000),
    Offset offset = Offset.zero,
    double blurRadius = 0.0,
    this.blurStyle = BlurStyle.normal,
  }) : super(color: color, offset: offset, blurRadius: blurRadius);

  @override
  Paint toPaint() {
    final Paint result = Paint()
      ..color = color
      ..maskFilter = MaskFilter.blur(this.blurStyle, blurSigma);
    assert(() {
      if (debugDisableShadows)
        result.maskFilter = null;
      return true;
    }());
    return result;
  }
}

现在我们可以像这样使用它:

new CustomBoxShadow(
  color: Colors.black,
  offset: new Offset(5.0, 5.0),
  blurRadius: 5.0,
  blurStyle: BlurStyle.outer
)

推荐阅读