You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何给Flutter自定义绘制的三角形光标添加圆角?

Flutter自定义光标添加圆角的解决方案

想要复刻带圆角的光标样式(目标效果如下),但当前用CustomPaint绘制的三角形光标无法添加圆角,尝试drawRRect未成功,以下是解决方案:

效果对比

  • 目标光标样式:
    目标光标样式
  • 当前未加圆角的效果:
    当前绘制效果

解决方案

由于目标形状并非标准矩形,无法直接用RRect实现圆角,需要通过在路径的每个转角处拼接圆弧来实现平滑过渡。具体修改如下:

  1. 统一定义圆角半径,方便调整大小;
  2. 将顶部尖角替换为圆弧;
  3. 对左下角、右下角的尖锐转角,用圆弧替代直线过渡;
  4. 保留原有的底部贝塞尔曲线,维持光标底部的弧度。

修改后的完整代码

import 'package:flutter/material.dart';
import 'dart:math';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Cursor'),
        ),
        body: Center(
          child: Transform.rotate(
            angle: pi,
            child: CustomPaint(
                size: const Size(60, 70),
                painter: CursorPainter()
            )
          )
        ),
      ),
    )
  );
}

class CursorPainter extends CustomPainter {
  // 可根据需求调整圆角半径
  static const double _cornerRadius = 8.0;

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;
    
    canvas.drawPath(drawPath(size.width, size.height), paint);
  }
  
  Path drawPath(double x, double y) {
    final path = Path();
    final topCenterX = x / 2;

    // 顶部圆角:用圆弧替换尖角
    path.moveTo(topCenterX + _cornerRadius, 0);
    path.arcToPoint(
      Offset(topCenterX - _cornerRadius, 0),
      radius: const Radius.circular(_cornerRadius),
      clockwise: false,
    );

    // 左侧边 + 左下角圆角
    path.lineTo(_cornerRadius, y);
    path.arcToPoint(
      Offset(0, y - _cornerRadius),
      radius: const Radius.circular(_cornerRadius),
      clockwise: false,
    );

    // 底部贝塞尔曲线(保留原有弧度)
    path.quadraticBezierTo(x / 2, y + 15, x - _cornerRadius, y);

    // 右下角圆角
    path.arcToPoint(
      Offset(x, y - _cornerRadius),
      radius: const Radius.circular(_cornerRadius),
      clockwise: false,
    );

    path.close();
    return path;
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

说明

  • 顶部圆弧通过arcToPoint逆时针绘制,形成平滑的圆角替代尖锐顶点;
  • 左右下角先绘制到圆角的起点位置,再通过圆弧过渡到转角另一侧,避免出现直角;
  • 修改_cornerRadius的值可以快速调整圆角大小,适配不同的光标尺寸。

内容的提问来源于stack exchange,提问作者zigg-zigg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:52:48