flutter 抽奖旋转大转盘

Untitled.gif

使用 CustomPainter 绘制好内容,然后再使用动画对整个对内容旋转固定的角度 。以下效果图由于是gif录制的不太流畅 看效果可以运行源码在最下面。

配置数据源

 void _loadImage() async {
    ui.Image? img = await loadImageFromAssets('images/ionc_rank_list.png');
    for (int x = 0 ; x < 12 ; x ++) {
      titles.add('T_$x');
      prices.add('P_$x');
      _images.add(img!);
    }
    setState(() {});
  }

开始旋转 随机0 到12个 指定停止到哪一个

  void drawClick() async {
    int res = Random().nextInt(12);
    print(res);
    angle = res * 360 / _images.length;
    _controller.forward();
    setState(() {});
  }

以下是 全部代码 可以直接在main 里面运行 图片自行换一下

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/services.dart' show rootBundle;
import 'package:scale_button/scale_button.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('扇形转盘'),
        ),
        body: SpinWheel(),
      ),
    );
  }
}

class SpinWheel extends StatefulWidget {
  const SpinWheel({Key? key}) : super(key: key);
  @override
  _SpinWheelState createState() => _SpinWheelState();
}

class _SpinWheelState extends State<SpinWheel> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  final List<ui.Image> _images = [];
  List<String> titles = [];
  List<String> prices = [];

  double angle = 0;

  @override
  void initState() {
    super.initState();

    initConfig();
    _loadImage();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _controller.dispose(); // 释放动画资源
    super.dispose();

  }

  void initConfig() {
    _controller = AnimationController(
      duration: const Duration(seconds: 3), // 定义动画持续时间
      vsync: this,
    );

    _animation = CurvedAnimation(parent: _controller, curve: Curves.decelerate);

    _animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller.reset(); // 重置动画
      }
    });
  }

  void _loadImage() async {
    ui.Image? img = await loadImageFromAssets('images/ionc_rank_list.png');
    for (int x = 0 ; x < 12 ; x ++) {
      titles.add('T_$x');
      prices.add('P_$x');
      _images.add(img!);
    }
    setState(() {});
  }


  //读取 assets 中的图片
  Future<ui.Image>? loadImageFromAssets(String path) async {
    ByteData data = await rootBundle.load(path);
    return decodeImageFromList(data.buffer.asUint8List());
  }
  

  void drawClick() async {
    int res = Random().nextInt(12);
    print(res);
    angle = res * 360 / _images.length;
    _controller.forward();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (_images.isEmpty) return Container();
    return Material(
      color: Colors.transparent,
      child: Container(
        width: 400,
        height: 400,
        padding: const EdgeInsets.only(top: 0),
        child: Stack(
          alignment: Alignment.center,
          children: [
            _rotationTransition(),
            ScaleButton(
              child: Image.asset(
                'images/icon_pointer.png',
                width: 160,
              ),
              onTap: (){
                drawClick();
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _rotationTransition(){
    return RotationTransition(
      turns: Tween(begin: 0.0, end: 5.0).animate(
        CurvedAnimation(
          parent: _controller,
          curve: Curves.ease,
        ),
      ),
      // turns: _animation,
      child: Transform.rotate(
        angle: angle * -(3.141592653589793 / 180), // 将角度转换为弧度
        child: Center(
          child: CustomPaint(
            size: const Size(360, 360),
            painter: SpinWheelPainter(titles: titles, images: _images, prices: prices),
          ),
        ),
      ),
    );
  }
}

class SpinWheelPainter extends CustomPainter {
  List <String> titles;
  List <ui.Image> images;
  List <String> prices ;
  SpinWheelPainter({required this.titles ,required this.images,required this.prices});

  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..style = PaintingStyle.fill;

    final double radius = size.width / 2;
    final double centerX = size.width / 2;
    final double centerY = size.height / 2;

    final int numSectors = titles.length; // 扇形数量
    final double sectorAngle = 2 * pi / numSectors; // 每个扇形的角度

    TextStyle textStyle = const TextStyle(
      color: Colors.red,
      fontSize: 12,
    );

    const double startAngle = 197 * pi / 180; // 15度的弧度值

    for (int i = 0; i < titles.length; i++) {
      final double currentStartAngle = startAngle + i * sectorAngle +1;
      final double currentSweepAngle = sectorAngle;
      paint.color = i % 2 == 0
          ? Colors.blue
          : const Color.fromRGBO( 251,232, 192,1); // 循环使用颜色数组

      canvas.drawArc(
        Rect.fromCircle(center: Offset(centerX, centerY), radius: radius),
        currentStartAngle,
        currentSweepAngle,
        true,
        paint,
      );

      // 旋转画布
      canvas.save();
      canvas.translate(centerX, centerY);
      canvas.rotate(currentStartAngle + currentSweepAngle / 2 + pi / 2); // 旋转45度
      canvas.translate(-centerX, -centerY);
      double img_width = 40;
      if(images.isNotEmpty){
        final imageRect = Rect.fromLTWH(
          centerX - img_width / 2,
          centerY - radius * 0.7 - img_width,
          img_width,
          img_width,
        );

        paintImage(
          canvas: canvas,
          rect: imageRect,
          image: images[i],
          fit: BoxFit.fill,
          alignment: Alignment.center,
          repeat: ImageRepeat.noRepeat,
          flipHorizontally: false,
          filterQuality: FilterQuality.low,
        );

      }


      // 添加文字
      final String text = titles[i];
      final TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: text,
          style: textStyle,
        ),
        textAlign: TextAlign.center,
        textDirection: TextDirection.ltr,
      );

      textPainter.layout();

      // 计算文字位置
      final double textX = centerX - textPainter.width / 2;
      final double textY = centerY - radius * 0.6;

      // 绘制文字
      textPainter.paint(canvas, Offset(textX, textY));

      final String text1 = prices[i];

      final TextPainter priceTextPainter = TextPainter(
        text: TextSpan(
          text: text1,
          style: textStyle,
        ),
        textAlign: TextAlign.center,
        textDirection: TextDirection.ltr,
      );

      priceTextPainter.layout();

      // 计算文字位置
      final double priceTextX = centerX - priceTextPainter.width / 2;
      final double priceTextY = centerY - radius * 0.5;

      // 绘制文字
      priceTextPainter.paint(canvas, Offset(priceTextX, priceTextY));

      canvas.restore(); // 恢复画布状态
    }
  }

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


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容