当前位置:主页 > 移动开发 > Android代码 >

Android通过交互实现贝塞尔曲线的绘制

时间:2022-07-14 08:19:26 | 栏目:Android代码 | 点击:

前言

之前几篇我们介绍了贝塞尔曲线的原理、绘制曲线和动效实现,这些都是代码预设好的,如果我们要根据需要自行绘制曲线,就需要使用交互来实现了。本篇我们先来介绍简单的交互式绘图,通过获取触控位置来设定贝塞尔曲线的控制点,从而实现交互式绘制曲线。

获取触控位置

第一个要解决的问题是如何获取手指在屏幕的触控位置。在 Flutter 中,提供了一个 Listener 组件,可以监听各类触控事件。Listener 的组件构造方法定义如下:

const Listener({
  Key? key,
  this.onPointerDown,
  this.onPointerMove,
  this.onPointerUp,
  this.onPointerHover,
  this.onPointerCancel,
  this.onPointerSignal,
  this.behavior = HitTestBehavior.deferToChild,
  Widget? child,
}) 

其中onPointerXX都是触控事件的回调方法,在回调里会携带触控的位置信息,具体的参数如下:

下面是点按后获取触控位置为例代码,使用的话还是比较简单的。当然,这里要说明一下,如果只是单纯地获取触控事件,而不需要触控的细节(比如位置,触控力度等),那么官方推荐是使用更高封装层级的手势识别组件 GestureDetector

Listener(
  onPointerUp: ((event) {
    print('position: ${event.localPosition}');
  }),
  behavior: HitTestBehavior.opaque,
  child: ...
),

交互绘制实现

有了上面的基础,我们获取到触控点位置后,刷新界面触发 Canvas 重绘即可。不过这里有个问题,我们希望是可以连续绘制,而不是只能绘制一条曲线。比如说我们点按了2个点,那就绘制直线;3个点就绘制2阶贝塞尔曲线;4个点绘制3阶贝塞尔曲线;4个点以上,把前一条曲线的结束点当做新的曲线的起点,按上述的方式循环绘制。这样我们就能够保证曲线是连续的了。这里可以通过递归方式实现,代码如下:

void drawCurves(Canvas canvas, Paint paint, List<Offset> points) {
    if (points.length <= 1) {
      return;
    }
    if (points.length == 2) {
      canvas.drawLine(points[0], points[1], paint);
      return;
    }
    if (points.length == 3) {
      _draw2OrderBezierCurves(canvas, paint, points);
      return;
    }
    if (points.length == 4) {
      _draw3OrderBezierCurves(canvas, paint, points);
      return;
    }
    var subPoints = points.sublist(0, 4);
    drawCurves(canvas, paint, subPoints);
    drawCurves(canvas, paint, points.sublist(3));
}

此外,考虑可能绘制的不是我们想要的效果,要支持撤销功能,因此我们加了一个按钮,点击按钮可以删除最近添加的点,从而实现撤销功能。我们用 ScaffoldfloatingActionButton 实现,逻辑很简单,就是如果点数组不为空的话,就删除最后一个点,然后刷新界面就好了。

floatingActionButton: IconButton(
  onPressed: () {
    if (points.isNotEmpty) {
      points.removeLast();
      setState(() {});
    }
  },
  icon: Icon(
    Icons.backspace,
    color: Colors.blue,
  ),
),

绘制代码

有了上面的基础,绘制代码就简单很多了,我们用一个数组存储已经点击的点,然后通过这些点递归调用绘制方法就可以 实现交互式绘制了,完整代码如下所示,这里我们把控制点使用圆圈绘制出来了。

class GestureBezierDemo extends StatefulWidget {
  GestureBezierDemo({Key? key}) : super(key: key);

  @override
  State<GestureBezierDemo> createState() => _GestureBezierDemoState();
}

class _GestureBezierDemoState extends State<GestureBezierDemo> {
  var points = <Offset>[];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Listener(
        onPointerUp: ((event) {
          points.add(event.localPosition);
          setState(() {});
        }),
        behavior: HitTestBehavior.opaque,
        child: CustomPaint(
          foregroundPainter: GestureBezierPainter(points: points),
          child: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            color: Color(0xFFF5F5F5),
          ),
        ),
      ),
      floatingActionButton: IconButton(
        onPressed: () {
          if (points.isNotEmpty) {
            points.removeLast();
            setState(() {});
          }
        },
        icon: Icon(
          Icons.backspace,
          color: Colors.blue,
        ),
      ),
    );
  }
}

class GestureBezierPainter extends CustomPainter {
  GestureBezierPainter({required this.points});
  final List<Offset> points;
  @override
  void paint(Canvas canvas, Size size) {
    print(size);
    canvas.drawColor(Color(0xFFF1F1F1), BlendMode.color);
    var paint = Paint()..color = Color(0xFFE53020);
    paint.strokeWidth = 2.0;
    paint.style = PaintingStyle.stroke;
    for (var point in points) {
      canvas.drawCircle(point, 2.0, paint);
    }
    paint.color = Color(0xFF2480F0);
    drawCurves(canvas, paint, points);
  }

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

  void drawCurves(Canvas canvas, Paint paint, List<Offset> points) {
    if (points.length <= 1) {
      return;
    }
    if (points.length == 2) {
      canvas.drawLine(points[0], points[1], paint);
      return;
    }
    if (points.length == 3) {
      _draw2OrderBezierCurves(canvas, paint, points);
      return;
    }
    if (points.length == 4) {
      _draw3OrderBezierCurves(canvas, paint, points);
      return;
    }
    var subPoints = points.sublist(0, 4);
    drawCurves(canvas, paint, subPoints);
    drawCurves(canvas, paint, points.sublist(3));
  }

  _draw3OrderBezierCurves(Canvas canvas, Paint paint, List<Offset> points) {
    assert(points.length == 4);
    var yGap = 60.0;
    var path = Path();
    path.moveTo(points[0].dx, points[0].dy);
    for (var t = 1; t <= 100; t += 1) {
      var curvePoint = BezierUtil.get3OrderBezierPoint(
          points[0], points[1], points[2], points[3], t / 100.0);

      path.lineTo(curvePoint.dx, curvePoint.dy);
    }
    canvas.drawPath(path, paint);
  }

  _draw2OrderBezierCurves(Canvas canvas, Paint paint, List<Offset> points) {
    assert(points.length == 3);
    var path = Path();
    path.moveTo(points[0].dx, points[0].dy);
    for (var t = 1; t <= 100; t += 1) {
      var curvePoint = BezierUtil.get2OrderBezierPoint(
          points[0], points[1], points[2], t / 100.0);

      path.lineTo(curvePoint.dx, curvePoint.dy);
    }
    canvas.drawPath(path, paint);
  }
}

运行效果

运行效果如下图所示。

总结

本篇其实更多地是介绍获取屏幕触控位置的内容,要实现交互式绘制就需要掌握用户的触控行为,从而绘制对应的图案。接下来我们会继续探索更多交互行为,做更多的交互式绘制探索。

您可能感兴趣的文章:

相关文章