【问题标题】:How to draw path along circle in Flutter?如何在 Flutter 中沿着圆圈绘制路径?
【发布时间】:2020-04-16 15:09:12
【问题描述】:

我想在 Flutter 中使用 Custom Painter 沿着圆(例如正弦波或贝塞尔曲线)绘制任意路径。

我正在寻找一种使用 Matrix4 转换此路径的方法,但找不到合适的方法。

假设我从以下布局开始:

我想实现以下投影:

请找到最小的起始示例。我试图使用矩阵转换旋转mpath,但无法提出正确的转换。例如:

final matrix = Matrix4.identity()
      ..setEntry(0, 1, 2)
      ..rotateY(val * math.pi)
      ..translate(-120.0);
    canvas.transform(matrix.storage);
import 'dart:math' as math;
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyAppHome(),
    );
  }
}

class MyAppHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Center(
        child: SizedBox(
          height: 300,
          width: 300,
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: OnCriclePainter(),
    );
  }
}

class OnCriclePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    canvas.saveLayer(null, Paint());

    canvas.save();
    canvas.translate(size.width / 2, size.height / 2);
    final paint = Paint()
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;
    Path mpath = new Path();
    var val = 1.0;
    mpath.relativeQuadraticBezierTo(40, val * 100, 80, 0);
    mpath.relativeQuadraticBezierTo(40, -val * 100, 80, 0);

    canvas.drawPath(mpath, paint);

// how to place it onto the circle?

    canvas.restore();

    canvas.drawCircle(
      Offset(size.width / 2, size.height / 2),
      size.width / 2,
      Paint()
        ..strokeWidth = 1
        ..style = PaintingStyle.stroke,
    );

    canvas.restore();
  }

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

【问题讨论】:

    标签: flutter dart graphics


    【解决方案1】:

    你必须像这样使用 conicTo 函数:

        final path = Path()
          ..moveTo(x, y)
          ..conicTo(double x1, double y1, double x2, double y2, double w);
    

    来自文档:

    使用控制点 (x1,y1) 和权重 w,添加从当前点到给定点 (x2,y2) 的贝塞尔曲线段。如果权重大于1,则曲线为双曲线;如果权重等于 1,则为抛物线;如果小于 1,则为椭圆。

    或者使用 quadraticBezierTo 函数

    quadraticBezierTo(double x1, double y1, double x2, double y2)
    

    此链接有助于理解 quadraticBezierTo https://www.youtube.com/watch?v=1ToqYMSnNhA

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多