flutter 自定义摇杆键盘 flutter摇杆键盘
记一次摇杆键盘开发过程
步骤:
- 使用Container组件利用BoxDecoration设置为圆形
- 先包裹一个GestureDetector,利用onPanUpdate属性监听滑动坐标(Offset p = details.localPosition;),利用onPanEnd监听松开坐标(p = Offset(0, 0)),松开后 摇杆归零
- GestureDetector包裹一个CustomPaint,利用CustomPaint画一个实心圆 作为摇杆
- 根据p的位置更新摇杆的坐标
防止摇杆超过Container的方法(仅在Container圆内):
void drawercic(Canvas canvas) {
//等于0时候在中间
double rx = _wide / 2;
double ry = _hight / 2;
double r = rx;
if (p.dx == 0 && p.dy == 0) {
canvas.drawCircle(Offset(_wide / 2, _hight / 2), 10, paintline);
} else {
double x;
double y;
if (p.dx <= 0) {
x = 1;
} else {
x = p.dx;
}
if (p.dy <= 0) {
y = 1;
} else {
y = p.dy;
}
if (((x - rx) * (x - rx) + (y - ry) * (y - ry)) > rx * rx) {
double x1;
double y1;
if ((x > rx && y > rx) || (x <= rx && y <= rx)) {
if (x > rx) {
x1 = ry +
cos(atan((_hight / 2 - y) / (_wide / 2 - x))) * (_wide / 2);
} else {
x1 = ry -
cos(atan((_hight / 2 - y) / (_wide / 2 - x))) * (_wide / 2);
}
if (y > rx) {
y1 = rx +
sin(atan((_hight / 2 - y) / (_wide / 2 - x))) * (_wide / 2);
} else {
y1 = rx -
sin(atan((_hight / 2 - y) / (_wide / 2 - x))) * (_wide / 2);
}
canvas.drawCircle(Offset(x1, y1), 10, paintline);
} else {
if (x < rx && y > rx) {
y1 = r + sin(atan((y - r) / (r - x))) * r;
x1 = r - cos(atan((y - r) / (r - x))) * r;
canvas.drawCircle(Offset(x1, y1), 10, paintline);
} else {
y1 = r - sin(atan((y - r) / (r - x))) * r;
x1 = r + cos(atan((y - r) / (r - x))) * r;
canvas.drawCircle(Offset(x1, y1), 10, paintline);
}
}
} else {
canvas.drawCircle(
Offset(p.dx < 0 ? 0 : (p.dx > _wide ? _wide : p.dx),
p.dy < 0 ? 0 : (p.dy > _hight ? _hight : p.dy)),
5,
paintline);
}
}
}
画笔属性:
Paint paintline = Paint()
..color = Colors.blue //画笔颜色
..strokeCap = StrokeCap.round //画笔笔触类型
..isAntiAlias = true //是否启动抗锯齿
..style = PaintingStyle.fill//填充
..strokeWidth = 1; //画笔的宽度