Flutter-自定义画板

news2024/10/6 4:08:17

效果

功能

  • 支持绘制线、圆、矩形,支持拓展
  • 支持撤回上一步
  • 支持清空画板
  • 支持自定义画笔颜色,宽度

实现

定义绘制类型

/// 类型
enum ShapeType {
  //线
  line,
  //圆
  circle,
  //矩形
  rectangle,
  //拓展
}

定义绘制抽象类

import 'dart:ui';

/// 绘制抽象类
abstract class Shape {
  void draw(
    Canvas canvas,
    List<Offset> points,
    Paint paint,
  );
}

实现线、圆、矩形绘制

/// 绘制圆
class CircleShape implements Shape {
  @override
  void draw(Canvas canvas, List<Offset> points, Paint paint) {
    if (points.length >= 2) {
      double radius = (points[points.length - 1] - points[1]).distance / 2;
      paint.style = PaintingStyle.stroke;
      canvas.drawCircle(points[0], radius, paint);
    }
  }
}

/// 绘制线
class LineShape implements Shape {
  @override
  void draw(Canvas canvas, List<Offset> points, Paint paint) {
    for (int i = 0; i < points.length - 1; i++) {
      canvas.drawLine(points[i], points[i + 1], paint);
    }
  }
}

/// 绘制方
class RectangleShape implements Shape {
  @override
  void draw(Canvas canvas, List<Offset> points, Paint paint) {
    if (points.length >= 2) {
      final rect = Rect.fromPoints(points[0], points[points.length - 1]);
      paint.style = PaintingStyle.stroke;
      canvas.drawRect(rect, paint);
    }
  }
}

定义工厂类 factory

/// 根据绘制类型返回具体绘制对象
Shape getShape(ShapeType type) {
  switch (type) {
    case ShapeType.line:
      return LineShape();
    case ShapeType.circle:
      return CircleShape();
    case ShapeType.rectangle:
      return RectangleShape();
  }
}

定义笔画参数对象

/// 笔画参数对象
class DrawingStroke {
  Color color;
  double width;
  List<Offset> points;
  ShapeType type;

  DrawingStroke({
    this.color = Colors.black,
    this.width = 2.0,
    this.points = const [],
    this.type = ShapeType.line,
  });
}

定义绘制控制器

/// 绘制控制器
class DrawingController {
  final _strokes = <DrawingStroke>[];
  final _listeners = <VoidCallback>[];

  // 所有绘制笔画数据
  List<DrawingStroke> get strokes => List.unmodifiable(_strokes);
  // 画笔颜色
  Color selectedColor = Colors.black;
  // 画笔宽度
  double strokeWidth = 2.0;
  // 绘制类型
  ShapeType selectedType = ShapeType.line;

  // 开始绘制
  void startDrawing(Offset point) {
    _strokes.add(DrawingStroke(
      color: selectedColor,
      width: strokeWidth,
      points: [point],
      type: selectedType,
    ));
    _notifyListeners();
  }

  // 正在绘制
  void updateDrawing(Offset point) {
    if (_strokes.isNotEmpty) {
      _strokes.last.points.add(point);
      _notifyListeners();
    }
  }

  // 结束当前笔画绘制
  void endDrawing() {
    _notifyListeners();
  }

  // 撤回一笔
  void undo() {
    if (_strokes.isNotEmpty) {
      _strokes.removeLast();
      _notifyListeners();
    }
  }

  // 清空数据
  void clear() {
    _strokes.clear();
    _notifyListeners();
  }

  // 设置画笔颜色
  void setColor(Color color) {
    selectedColor = color;
    _notifyListeners();
  }

  // 设置画笔宽度
  void setStrokeWidth(double width) {
    strokeWidth = width;
    _notifyListeners();
  }

  // 设置绘制类型
  void setDrawingType(ShapeType type) {
    selectedType = type;
    _notifyListeners();
  }

  void _notifyListeners() {
    for (var listener in _listeners) {
      listener();
    }
  }

  void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }

  void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }
}

定义画板类DrawingBoard

class DrawingBoard extends StatefulWidget {
  final DrawingController controller;

  const DrawingBoard({Key? key, required this.controller}) : super(key: key);

  @override
  State<StatefulWidget> createState() => DrawingBoardState();
}

class DrawingBoardState extends State<DrawingBoard> {
  @override
  void initState() {
    super.initState();
    widget.controller.addListener(_updateState);
  }

  void _updateState() {
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    widget.controller.removeListener(_updateState);
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, size) {
      return SizedBox(
        width: size.maxWidth,
        height: size.maxHeight,
        child: GestureDetector(
          onPanStart: (details) {
            widget.controller.startDrawing(details.localPosition);
          },
          onPanUpdate: (details) {
            widget.controller.updateDrawing(details.localPosition);
          },
          onPanEnd: (_) {
            widget.controller.endDrawing();
          },
          child: CustomPaint(
            painter: DrawingPainter(strokes: widget.controller.strokes),
            size: Size.infinite,
          ),
        ),
      );
    });
  }
}

class DrawingPainter extends CustomPainter {
  final Paint drawPaint = Paint();

  DrawingPainter({required this.strokes});

  List<DrawingStroke> strokes;

  @override
  void paint(Canvas canvas, Size size) {
    for (var stroke in strokes) {
      drawPaint
        ..color = stroke.color
        ..strokeCap = StrokeCap.round
        ..strokeWidth = stroke.width;

      Shape shape = getShape(stroke.type);
      shape.draw(canvas, stroke.points, drawPaint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
使用画板
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_xy/xydemo/drawingboard/drawing/type.dart';
import 'package:flutter_xy/xydemo/drawingboard/drawing/view.dart';

import 'drawing/controller.dart';

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

  @override
  DrawingPageState createState() => DrawingPageState();
}

class DrawingPageState extends State<DrawingPage> {
  final _controller = DrawingController();

  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
  }

  @override
  void dispose() {
    super.dispose();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Row(
          children: [
            SizedBox(
              width: 120,
              child: ListView(
                scrollDirection: Axis.vertical,
                padding: const EdgeInsets.symmetric(horizontal: 20),
                children: [
                  const SizedBox(width: 10),
                  _buildText("操作"),
                  const SizedBox(width: 10),
                  _buildButton('Undo', () => _controller.undo()),
                  const SizedBox(width: 10),
                  _buildButton('Clear', () => _controller.clear()),
                  const SizedBox(width: 10),
                  _buildText("画笔颜色"),
                  const SizedBox(width: 10),
                  _buildColorButton(Colors.red),
                  const SizedBox(width: 10),
                  _buildColorButton(Colors.blue),
                  const SizedBox(width: 10),
                  _buildText("画笔宽度"),
                  const SizedBox(width: 10),
                  _buildStrokeWidthButton(2.0),
                  const SizedBox(width: 10),
                  _buildStrokeWidthButton(5.0),
                  const SizedBox(width: 10),
                  _buildText("画笔类型"),
                  const SizedBox(width: 10),
                  _buildTypeButton(ShapeType.line, '线'),
                  const SizedBox(width: 10),
                  _buildTypeButton(ShapeType.circle, '圆'),
                  const SizedBox(width: 10),
                  _buildTypeButton(ShapeType.rectangle, '方'),
                ],
              ),
            ),
            Expanded(
              child: Column(
                children: [
                  Expanded(
                    child: DrawingBoard(
                      controller: _controller,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildText(String text) {
    return Text(
      text,
      style: const TextStyle(
        fontSize: 12,
        fontWeight: FontWeight.w600,
      ),
    );
  }

  Widget _buildButton(String text, VoidCallback onPressed) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(text),
    );
  }

  Widget _buildColorButton(Color color) {
    return ElevatedButton(
      onPressed: () => _controller.setColor(color),
      style: ElevatedButton.styleFrom(primary: color),
      child: const SizedBox(width: 30, height: 30),
    );
  }

  Widget _buildStrokeWidthButton(double width) {
    return ElevatedButton(
      onPressed: () => _controller.setStrokeWidth(width),
      child: Text(width.toString()),
    );
  }

  Widget _buildTypeButton(ShapeType type, String label) {
    return ElevatedButton(
      onPressed: () => _controller.setDrawingType(type),
      child: Text(label),
    );
  }
}

运行效果如下图:

详情见 github.com/yixiaolunhui/flutter_xy

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1621659.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

云原生Service Mesh服务网格简单介绍

serviceMesh是什么 Service Mesh是一个用于处理服务间通信的基础设施层&#xff0c;旨在实现云原生应用复杂服务拓扑中的可靠请求传递。其基本构成是一组与应用一起部署的轻量级网络代理&#xff0c;这些代理对应用来说是透明的。Service Mesh通过统一的方式来控制和处理服务间…

数据结构-二叉树-链式

一、链式二叉树的结构 typedef int BTNodeDataType; typedef struct BTNode {BTNodeDataType data;struct BTNode* left;struct BTNode* right; }BTNode; 二叉树的前中后序遍历 前序&#xff1a;根左右 中序&#xff1a;左根右 后序&#xff1a;左右根 void PreOrder(BTNo…

大语言模型Ollama

版权声明 本文原创作者&#xff1a;谷哥的小弟作者博客地址&#xff1a;http://blog.csdn.net/lfdfhl Ollama简介 Ollama是一个开源的大语言模型平台&#xff0c;它允许用户在本地环境中运行、创建和共享大型语言模型。Ollama提供了丰富的功能和特性&#xff0c;使得用户可以…

Jenkins - macOS 上安装

文章目录 关于 JenkinsmacOS 上安装 Jenkins方式一&#xff1a;brew方式二&#xff1a;tomcat Jenkins war 关于 Jenkins 官网上下载Jenkins并将其安装到持续集成服务器 https://jenkins.io/download/ macOS 上安装 Jenkins 现在本 macOS 上测试 https://www.jenkins.io/do…

更新至2022年上市公司数字化转型数据合集(四份数据合集)

更新至2022年上市公司数字化转型数据合集&#xff08;四份数据合集&#xff09; 一、2000-2022年上市公司数字化转型数据&#xff08;年报词频、文本统计&#xff09; 二、2007-2022年上市公司数字化转型数据&#xff08;年报和管理层讨论&#xff09;&#xff08;含原始数据…

Golang基础4-type、go测试

type相关 别名&#xff1a;本质上是更好的理解代码&#xff0c;比如byte(uint8)、rune(int32) 定义新类型&#xff0c;那么就相当于时struct了 package mainimport ("fmt""strconv" )// XInt 别名,在编译的时候会直接替换int type XInt int// YInt 自定…

线性代数基础1向量

1、向量是什么 1.1、向量的定义 在数学中&#xff0c;向量&#xff08;也称为欧几里得向量、几何向量、矢量&#xff09;&#xff0c;指具有大小和方向的量。它可以形象化地表示为带箭头的线段。箭头所指&#xff1a;代表向量的方向&#xff1b;线段长度&#xff1a;代表向量的…

W801学习笔记十四:掌机系统——菜单——尝试打造自己的UI

未来将会有诸多应用&#xff0c;这些应用将通过菜单进行有序组织和管理。因此&#xff0c;我们需要率先打造好菜单。 LCD 驱动通常是直接写屏的&#xff0c;虽然速度较快&#xff0c;但用于界面制作则不太适宜。所以&#xff0c;最好能拥有一套 UI 框架。如前所述&#xff0c;…

面试二十一、红黑树

性质&#xff1a; 插入&#xff1a; 旋转&#xff1a;

Git之merge与rebase操作命令及问题

背景&#xff1a;之前一直使用的是 merge 来实现两分支的合并代码操作&#xff0c;遇到冲突&#xff0c;解决完冲突从头 add 、commit 、push 再次操作一遍提交操作就没啥事了。但后来的大型项目是 多人协同开发&#xff0c;前端带头人提议倡导使用 rebase 来合并分支&#xff…

【MySQL】libmysqlclient-dev安装失败

报错内容如下&#xff1a; 下列软件包有未满足的依赖关系&#xff1a; libmysqlclient-dev : 依赖: libssl-dev 但是它将不会被安装 依赖: zlib1g-dev 但是它将不会被安装 E: 无法修正错误&#xff0c;因为您要求某些软件包保持现状&#xff0c;就是它们破坏了软件包间的依赖关…

FRPC+PHP+MYSQL+APACHE2=个人网站

应用背景有公网需求,但是又不想去买又贵又低配置的服务器,然后方案就应运而生 frp/README_zh.md at dev fatedier/frp (github.com) 在这里, FRPC作为内网穿透服务, PHPMYSQLAPACHE2,作为网站搭建,具体细节不细讲, 但是在我的/var/www/html下面 linaroHinlink:/var/www/h…

flutter ios Firebase 消息通知错误 I-COR000005,I-FCM001000 解决

*前提是已经 使用firebase-tools 已经给 Flutter 加入了 消息通知相关配置。教程>> 一、I-COR000005 10.22.0 - [FirebaseCore][I-COR000005] No app has been configured yet. import Firebase....FirebaseApp.configure() 10.22.0 - [FirebaseMessaging][I-FCM001000…

Golang | Leetcode Golang题解之第48题旋转图像

题目&#xff1a; 题解&#xff1a; func rotate(matrix [][]int) {n : len(matrix)// 水平翻转for i : 0; i < n/2; i {matrix[i], matrix[n-1-i] matrix[n-1-i], matrix[i]}// 主对角线翻转for i : 0; i < n; i {for j : 0; j < i; j {matrix[i][j], matrix[j][i]…

Android某钉数据库的解密分析

声明 1 本文章中所有内容仅供学习交流&#xff0c;抓包内容、敏感网址、数据接口均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则由此产生的一切后果均与作者无关&#xff01; 目的 1 解密app数据库&#xff0c;用数据库软件打开查看信息内容 入手…

探索人工智能的边界:GPT 4.0与文心一言 4.0免费使用体验全揭秘!

探索人工智能的边界&#xff1a;GPT与文心一言免费试用体验全揭秘&#xff01; 前言免费使用文心一言4.0的方法官方入口进入存在的问题免费使用文心一言4.0的方法 免费使用GPT4.0的方法官方入口进入存在的问题免费使用GPT4.0的方法 前言 未来已来&#xff0c;人工智能已经可以…

前端css中keyframes(关键帧)的简单使用

前端css中keyframes的使用 一、前言二、例子&#xff08;一&#xff09;、例子源码1&#xff08;二&#xff09;、源码1运行效果1.视频效果2.截图效果 三、结语四、定位日期 一、前言 关键帧keyframes是css动画的一种&#xff0c;主要用于定义动画过程中某一阶段的样式变化&am…

[2021年最新]国产时序性数据TDenige入门

一、TDenige简介 TDengine&#xff1a;是涛思数据面对高速增长的物联网大数据市场和技术挑战推出的创新性的大数据处理产品&#xff0c;它不依赖任何第三方软件&#xff0c;也不是优化或包装了一个开源的数据库或流式计算产品&#xff0c;而是在吸取众多传统关系型数据库、NoS…

Prompt-to-Prompt Image Editing with Cross Attention Control

Prompt-to-Prompt Image Editing with Cross Attention Control TL; DR&#xff1a;prompt2prompt 提出通过替换 UNet 中的交叉注意力图&#xff0c;在图像编辑过程中根据新的 prompt 语义生图的同时&#xff0c;保持图像整体布局结构不变。从而实现了基于纯文本&#xff08;不…

Checkpoint机制和生产配置

1.前提 在将Checkpoint之前&#xff0c;先回顾一下flink处理数据的流程&#xff1a; 2. 概述 Checkpoint机制&#xff0c;又叫容错机制&#xff0c;可以保证流式任务中&#xff0c;不会因为异常时等原因&#xff0c;造成任务异常退出。可以保证任务正常运行。 &#xff08;1&…