有没有办法在容器周围放置渐变色边框?

问题描述 投票:0回答:2

我有:

Container(
        decoration: BoxDecoration( 
          borderRadius: BorderRadius.circular(35),
          border: Border.all(
            color: const Color(0xFFE800E8),//<---- Insert Gradient Here 
            width: 1.5,
          )
        ),
),

这是边框的视觉表示,当前为粉红色,这就是我想要制作的渐变:

flutter flutter-layout border
2个回答
11
投票

我不确定是否有更简单的方法。但你可以使用几个容器来构建它,如下所示:

Container(
  decoration: BoxDecoration(
    gradient: LinearGradient(
      colors: [
        Colors.black,
        Colors.pinkAccent,
      ],
    ),
    borderRadius: BorderRadius.circular(35),
  ),
  height: 100,
  child: Padding(
    padding: const EdgeInsets.all(1.5),
    child: Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(35),
      ),
      child: Center(
        child: Text('Enter further widgets here'),
      ),
    ),
  ),
),


0
投票

我们可以通过创建自己的BoxBorder来实现。我在下面添加一个片段。

import 'package:flutter/material.dart';

class GradientBoxBorder extends BoxBorder {
  final Gradient gradient;
  final double width;

  const GradientBoxBorder({
    required this.gradient,
    this.width = 1.0,
  });

  @override
  BorderSide get bottom => BorderSide.none;

  @override
  BorderSide get top => BorderSide.none;

  @override
  EdgeInsetsGeometry get dimensions => EdgeInsets.all(width);

  @override
  bool get isUniform => true;

  @override
  void paint(
    Canvas canvas,
    Rect rect, {
    TextDirection? textDirection,
    BoxShape shape = BoxShape.rectangle,
    BorderRadius? borderRadius,
  }) {
    if (shape == BoxShape.rectangle) {
      if (borderRadius != null) {
        _paintRRect(canvas, rect, borderRadius);
      } else {
        _paintRect(canvas, rect);
      }
    } else {
      _paintCircle(canvas, rect);
    }
  }

  void _paintRect(Canvas canvas, Rect rect) {
    final paint = Paint()
      ..shader = gradient.createShader(rect)
      ..strokeWidth = width
      ..style = PaintingStyle.stroke;
    canvas.drawRect(rect, paint);
  }

  void _paintRRect(Canvas canvas, Rect rect, BorderRadius borderRadius) {
    final paint = Paint()
      ..shader = gradient.createShader(rect)
      ..strokeWidth = width
      ..style = PaintingStyle.stroke;
    final rrect = RRect.fromRectAndCorners(
      rect,
      topLeft: borderRadius.topLeft,
      topRight: borderRadius.topRight,
      bottomLeft: borderRadius.bottomLeft,
      bottomRight: borderRadius.bottomRight,
    );
    canvas.drawRRect(rrect, paint);
  }

  void _paintCircle(Canvas canvas, Rect rect) {
    final paint = Paint()
      ..shader = gradient.createShader(rect)
      ..strokeWidth = width
      ..style = PaintingStyle.stroke;
    canvas.drawCircle(rect.center, rect.shortestSide / 2, paint);
  }

  @override
  ShapeBorder scale(double t) {
    return this;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.