简介
先来张图,看一下最终效果
关闭和确定
- 关闭和确定功能对应的是界面左下角叉号,和右下角对钩,关闭按钮仅做取消当次涂鸦,读者可自行设置点击后功能,也可自行更改相应ui。选择功能点击后会执行一段把当前涂鸦后的图片合成并保存到本地的操作。具体请看示例代码。
颜色选择
- 颜色选择功能可选择和标识当前涂鸦颜色,和指示当前涂鸦颜色的选中状态(以白色外圈标识)。切换颜色后下一次涂鸦即会使用新的颜色。
撤销功能
- 撤销功能可撤销最近的一次涂鸦。如没有涂鸦时显示置灰的撤销按钮。
清除功能
- 清除功能可清除所有涂鸦,如当前没有任何涂鸦时显示置灰的清除按钮。
涂鸦图片的放大和缩小
- 可双指滑动切换涂鸦放大缩小的效果。
放大缩小后按照新的线条粗细继续涂鸦
- 涂鸦放大或缩小后,涂鸦线条会随之放大和缩小,此时如果继续涂鸦,则新涂鸦显示的粗细程度与放大或缩小后的线条粗细程度保持一致。
保存涂鸦图片到本地。
- flutter涂鸦后的图片可合成新图片并保存到本地路径。
代码介绍
涂鸦颜色选择组件。
主要是显示为可配置的圆点和外圈
circle_ring_widget.dart
import 'package:flutter/material.dart'; class circleringwidget extends statelesswidget { late bool isshowring; late color dotcolor; circleringwidget(this.isshowring,this.dotcolor, {super.key}); @override widget build(buildcontext context) { return custompaint( painter: circleandringpainter(isshowring,dotcolor), size: const size(56.0, 81.0), // 调整尺寸大小 ); } } class circleandringpainter extends custompainter { late bool isshowring; late color dotcolor; circleandringpainter(this.isshowring,this.dotcolor); @override void paint(canvas canvas, size size) { paint circlepaint = paint() ..color = dotcolor // 设置圆点的颜色 ..strokecap = strokecap.round ..strokewidth = 1.0; paint ringpaint = paint() ..color = colors.white // 设置圆环的颜色 ..strokecap = strokecap.round ..strokewidth = 1.0 ..style = paintingstyle.stroke; offset center = size.center(offset.zero); // 画一个半径为10的圆点 canvas.drawcircle(center, 13.0, circlepaint); if(isshowring){ // 画一个半径为20的圆环 canvas.drawcircle(center, 18.0, ringpaint); } } @override bool shouldrepaint(covariant custompainter olddelegate) { return false; } }
存储颜色和食指划过点的数据类
color_offset.dart
import 'dart:ui'; class coloroffset{ late color color; late list<offset> offsets=[]; coloroffset(color color,list<offset> offsets){ this.color=color; this.offsets.addall(offsets); } }
具体涂鸦点的绘制
此处是具体绘制涂鸦点的自定义view。大家是不是觉得哇,好简单呢。两个循环一嵌套,瞬间所有涂鸦就都出来了。其实做这个功能时,我参考了其他各种涂鸦控件,但是总觉得流程非常复杂。难以理解。原因是他们的颜色和点在数据层面都是混合到一起的,而且还得判断哪里是新画的涂鸦线条,来回控制。用这个demo的结构,相信各位读者一看就能知道里面的思路
doodle_painter.dart
import 'package:flutter/cupertino.dart'; import 'color_offset.dart'; class doodleimagepainter extends custompainter { late map<int,coloroffset> newpoints; doodleimagepainter(this.newpoints); @override void paint(canvas canvas, size size) { newpoints.foreach((key, value) { paint paint = _getpaint(value.color); for(int i=0;i<value.offsets.length - 1;i++){ //最后一个画点,其他画线 if(i==value.offsets.length-1){ canvas.drawcircle(value.offsets[i], 2.0, paint); }else{ canvas.drawline(value.offsets[i], value.offsets[i + 1], paint); } } }); } paint _getpaint(color color){ return paint() ..color = color ..strokecap = strokecap.round ..strokewidth = 5.0; } @override bool shouldrepaint(covariant custompainter olddelegate) { return true; } }
涂鸦主要界面代码
- 包含整体涂鸦数据的构建
- 包含涂鸦图片的合成和本地存储
- 包含涂鸦颜色列表的自定义
- 包含涂鸦原图片的放大缩小
- 包含撤销一步和清屏功能
下面这些就是整体涂鸦相关功能代码,其中一些资源图片未提供,请根据需要自己去设计处获取。
import 'dart:io'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import '../player_base_control.dart'; import 'circle_ring_widget.dart'; import 'color_offset.dart'; import 'doodle_painter.dart'; class doodlewidget extends playerbasecontrollablewidget { final string snapshotpath; final valuechanged<bool>? completed; const doodlewidget(super.controller, {super.key, required this.snapshotpath, this.completed}); @override state<statefulwidget> createstate() => _doodlewidgetstate(); } class _doodlewidgetstate extends state<doodlewidget> { map<int, coloroffset> newpoints = {}; list<offset> points = []; int lineindex = 0; globalkey globalkey = globalkey(); int currentselect = 0; final double maxscale = 3.0; final double minscale = 1.0; list<color> colors = const [ color(0xffff0000), color(0xfffae03d), color(0xff6f52ff), color(0xffffffff), color(0xff000000) ]; transformationcontroller controller = transformationcontroller(); double realscale = 1.0; offset realtranslocation = offset.zero; late image currentimg; bool issaved = false; @override void initstate() { currentimg = image.memory(file(widget.snapshotpath).readasbytessync()); controller.addlistener(() { ///获取矩阵里面的缩放具体值 realscale = controller.value.entry(0, 0); ///获取矩阵里面的位置偏移量 realtranslocation = offset(controller.value.gettranslation().x, controller.value.gettranslation().y); }); super.initstate(); } @override widget build(buildcontext context) { return stack( children: [ positioned.fill(child: layoutbuilder( builder: (buildcontext context, boxconstraints constraint) { return interactiveviewer( panenabled: false, scaleenabled: true, maxscale: maxscale, minscale: minscale, transformationcontroller: controller, oninteractionstart: (scalestartdetails details) { // print("--------------oninteractionstart执行了 dx=${details.focalpoint.dx} dy=${details.focalpoint.dy}"); }, oninteractionupdate: (scaleupdatedetails details) { if (details.pointercount == 1) { /// 获取 x,y 拿到值后进行缩放偏移等换算 var x = details.focalpoint.dx; var y = details.focalpoint.dy; var point = offset( _getscaletranslatevalue(x, realscale, realtranslocation.dx), _getscaletranslatevalue( y, realscale, realtranslocation.dy)); setstate(() { points.add(point); newpoints[lineindex] = coloroffset(colors[currentselect], points); }); } }, oninteractionend: (scaleenddetails details) { // print("oninteractionend执行了"); if (points.length > 5) { newpoints[lineindex] = coloroffset(colors[currentselect], points); lineindex++; } // newpoints.addall({lineindex:coloroffset(colors[currentselect],points)}); //清空原数组 points.clear(); }, child: repaintboundary( key: globalkey, child: stack( alignment: alignmentdirectional.center, children: [ positioned.fill(child: currentimg), positioned.fill( child: custompaint(painter: doodleimagepainter(newpoints))), ], ), ), ); })), positioned( bottom: 0, left: 0, right: 0, child: _bottomactions(), ) ], ); } double _getscaletranslatevalue( double current, double scale, double translate) { return current / scale - translate / scale; } widget _bottomactions() { return container( height: 81, color: const color(0xaa17161f), child: row( children: [ /// 关闭按钮 sizedbox( width: 95, height: 81, child: center( child: gesturedetector( ontap: () { widget.completed?.call(false); }, child: image.asset( "images/icon_close_white.webp", width: 30, height: 30, scale: 3, package: "koo_daxue_record_player", ), ), ), ), const verticaldivider( thickness: 1, indent: 15, endindent: 15, color: colors.white, ), row( children: _colorlistwidget(), ), expanded(child: container()), /// 退一步按钮 sizedbox( width: 66, height: 81, child: gesturedetector( ontap: () { setstate(() { if (lineindex > 0) { lineindex--; newpoints.remove(lineindex); } }); }, child: center( child: image.asset( lineindex == 0 ? "images/icon_undo.webp" : "images/icon_undo_white.webp", width: 30, height: 30, scale: 3, package: "koo_daxue_record_player", )), ), ), /// 清除按钮 sizedbox( width: 66, height: 81, child: center( child: gesturedetector( ontap: () { setstate(() { lineindex = 0; newpoints.clear(); }); }, child: image.asset( lineindex == 0 ? "images/icon_clear_doodle.webp" : "images/icon_clear_doodle_white.webp", width: 30, height: 30, scale: 3, package: "koo_daxue_record_player", ), )), ), const verticaldivider( thickness: 1, indent: 15, endindent: 15, color: colors.white, ), /// 确定按钮 sizedbox( width: 85, height: 81, child: center( child: gesturedetector( ontap: () { if (issaved) return; issaved = true; if (newpoints.isempty) { widget.completed?.call(false); return; } savedoodle(widget.snapshotpath).then((value) { if (value) { widget.completed?.call(true); } else { widget.completed?.call(false); } }); }, child: image.asset( "images/icon_finish_white.webp", width: 30, height: 30, scale: 3, package: "koo_daxue_record_player", ), )), ) ], ), ); } list<widget> _colorlistwidget() { list<widget> widgetlist = []; for (int i = 0; i < colors.length; i++) { color color = colors[i]; widgetlist.add(gesturedetector( ontap: () { setstate(() { currentselect = i; }); }, child: circleringwidget(i == currentselect, color), )); } return widgetlist; } future<bool> savedoodle(string imgpath) async { try { renderrepaintboundary boundary = globalkey.currentcontext!.findrenderobject() as renderrepaintboundary; ui.image image = await boundary.toimage(pixelratio: 3.0); bytedata? bytedata = await image.tobytedata(format: ui.imagebyteformat.png); uint8list pngbytes = bytedata!.buffer.asuint8list(); // 保存图片到文件 file imgfile = file(imgpath); await imgfile.writeasbytes(pngbytes); return true; } catch (e) { return false; } } }
以上就是flutter实现给图片添加涂鸦功能的详细内容,更多关于flutter给图片添加涂鸦的资料请关注代码网其它相关文章!
发表评论