简体   繁体   English

"Flutter Custom Paint 与路径交叉,但带有渐变和圆角"

[英]Flutter Custom paint cross with path but with gradient and rounded corners

I've just started getting to grips with Custom painter and I've created a basic cross but not sure how to make the corners rounded and make the colour a gradient?我刚开始接触自定义画家,我已经创建了一个基本的十字架,但不知道如何使角落变圆并使颜色成为渐变?

It seems a gradient requires createShader<\/code> which takes a rect<\/code> but I don't have one since I used paths.似乎渐变需要createShader<\/code> ,它需要一个rect<\/code> ,但我没有一个,因为我使用了路径。

Also I'd like to round the corners of the cross a little but not sure how that is done.我也想把十字架的拐角弄圆一点,但不知道是怎么做的。 I thought about creating rectangles but it doesn't seem to be possible to create slanted rectangles either.我考虑过创建矩形,但似乎也无法创建倾斜的矩形。

class CrossPainter extends CustomPainter {
  CrossPainter({this.bodyColour, this.strokeColour, this.stroke});
  final Color bodyColour;
  final Color strokeColour;
  final double stroke;
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint
      ..color = strokeColour
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeWidth = stroke;

    Paint paint1 = Paint();
    paint1
      ..color = bodyColour
      ..style = PaintingStyle.fill
      ..strokeWidth = 0;

    double width = size.width;
    double height = size.height;

    Path path = Path();
    path.addPolygon([Offset.zero, Offset(width / 4, 0), Offset(width, height), Offset(width - (width / 4), height)], true);
    Path path2 = Path();
    path2.addPolygon(
        [Offset(width, 0), Offset(width - (width / 4), 0), Offset(0, height), Offset(0 + (width / 4), height)], true);

    canvas.drawPath(path, paint1);
    canvas.drawPath(path2, paint1);
    // canvas.drawPath(path, paint); //border
    // canvas.drawPath(path2, paint); //border
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

You can freely use Rect on the Shader to fill gradient on rounded polygon drawn on the canvas.您可以在 Shader 上自由使用 Rect 来填充画布上绘制的圆角多边形上的渐变。 On my approach, I used the size defined on the canvas as a base for the Rect.在我的方法中,我使用画布上定义的大小作为 Rect 的基础。

Paint()
  ..style = PaintingStyle.stroke
  ..strokeCap = StrokeCap.round
  ..shader = gradient
      .createShader(Rect.fromLTWH(0.0, 0.0, size.width, size.height))
  ..strokeWidth = 20,

You can then add this paint object to the canvas that you're rendering.然后,您可以将此绘制对象添加到您正在渲染的画布上。

As for the gradient, you can define it however you like.至于渐变,你可以随意定义它。 But here's an example.但这里有一个例子。

const Gradient gradient = SweepGradient(
  startAngle: 1.25 * math.pi / 2,
  endAngle: 5.5 * math.pi / 2,
  tileMode: TileMode.repeated,
  colors: <Color>[
    Colors.blueAccent,
    Colors.lightBlueAccent,
  ],
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM