前言
最近在学习Flutter中 Canvas相关内容,今天尝试写了一个爱心Demo(程序员浪漫,表白神器!),感兴趣可以学习一下,如果你有更好的方法欢迎评论
效果图
代码示例
包含注释,这里只提供自定义的CustomPainter类
import 'dart:math';
import "dart:ui" as ui;
import 'dart:ui';
import 'package:flutter/material.dart';
/**
* @author Marinda
* @date 2023/3/29 10:58
* @desc 我的画板
*/
class MyCustomPainter extends CustomPainter{
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = Colors.blue..strokeWidth = 20..isAntiAlias = true ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.butt;
double centerWidth = size.width / 2;
double centerHeight = size.height / 2;
Path path = Path();
double width = size.width;
double height = size.height;
/*
* 绘制心形逻辑
* 1.绘制左半圆 addArc 默认从左到右进行绘制,并且抬笔重新画到右边
* 2.ArcTo绘制右半圆,不抬笔连前左半圆结束点开始绘制
* 3.接着从右半圆结束点绘制线段至中心结束点
* 4.再从线段起始点绘制左半圆 ,这里还是使用arcTo绘制,因为使用addArc则视为抬笔,则从①结束点开始绘制,不链接
* -100 是由于画圆会导致扩大,视觉差不居中
*/
path.moveTo(centerWidth, centerHeight);
path.addArc(Rect.fromLTWH(centerWidth-100, centerHeight, 100,100), 160 * (pi / 180), 200 * (pi / 180));
path.arcTo(Rect.fromLTWH(centerWidth, centerHeight, 100,100), 180 * (pi / 180), 200 * (pi / 180),false);
path.lineTo(centerWidth, centerHeight +200);
path.arcTo(Rect.fromLTWH(centerWidth - 100, centerHeight, 100,100), 160 * (pi / 180), 200 * (pi / 180),false);
canvas.drawPath(path, Paint()..color = Colors.red..strokeWidth = 4 ..style = PaintingStyle.stroke ..isAntiAlias = true);
/*
* @Author Marinda
* @Description 绘制文字
* @Date 15:18 2023/3/29
**/
ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(ui.ParagraphStyle(fontSize: 20));
ParagraphConstraints paragraphConstraints = ParagraphConstraints(width: 200);
paragraphBuilder.pushStyle(ui.TextStyle(color: Colors.blue));
paragraphBuilder.addText("XXX");
Paragraph paragraph = paragraphBuilder.build()..layout(paragraphConstraints);
canvas.drawParagraph(paragraph, Offset(centerWidth-20,centerHeight+70));
/*
* 绘制穿心路径
*/
ui.Path linePath = Path();
linePath.moveTo(centerWidth / 4, centerHeight+100);
linePath.lineTo(centerWidth+220, centerHeight +100);
//绘制当前线段向上箭头
linePath.relativeLineTo(-20, -20);
//绘制当前线段向下箭头
canvas.drawLine(Offset(centerWidth + 220,centerHeight+100), Offset(centerWidth +200,centerHeight +125), Paint()..color = Colors.red..strokeWidth = 4 ..style = PaintingStyle.stroke ..isAntiAlias = true);
canvas.drawPath(linePath, Paint()..color = Colors.red..strokeWidth = 4 ..style = PaintingStyle.stroke ..isAntiAlias = true..strokeMiterLimit = 3);
}
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
温馨提示
请注意看注释,关于Canvas中绘制Path中对于addArc 和 arcTo的区别,一个是默认抬笔重新绘制 一个是可选抬笔状态!
结束语
关于 Flutter学习笔记 —— CustomPainter自定义画布绘制爱心 就写到这里,对你有帮助的话!
- 点赞
- 收藏
谢谢你的观看!