OutlinedBorder
我需要帮助了解如何使用类在 Flutter 中创建自定义形状。
我不想使用剪裁,因为我想测试自定义形状是否最好也不会剪裁按钮子项。
如果有人会使用更简单的形状进行解释,我会更喜欢,但这是我创建的:
它的效果很好,只有蓝色部分会对点击做出反应并且涟漪不会泄漏,但是有两颗星,我希望它只是一颗星。
这是我的代码:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'dart:math' as Math;
class StarShape extends OutlinedBorder {
final BorderSide side;
StarShape({
this.side = const BorderSide(),
});
@override
OutlinedBorder copyWith({BorderSide? side}) {
return StarShape(side: side ?? const BorderSide());
}
@override
EdgeInsetsGeometry get dimensions => EdgeInsets.all(10);
@override
Path getInnerPath(Rect rect, {TextDirection? textDirection}) {
var _path = Path()
..addRect(rect.deflate(25))
..close();
return _path;
}
@override
Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
rect = rect.inflate(15);
var mid = rect.width / 2;
var min = Math.min(rect.width, rect.height);
var half = min / 2;
mid = mid - half;
var path = Path();
// top left
path.moveTo(mid + half * 0.5, half * 0.84);
// top right
path.lineTo(mid + half * 1.5, half * 0.84);
// bottom left
path.lineTo(mid + half * 0.68, half * 1.45);
// top tip
path.lineTo(mid + half * 1.0, half * 0.5);
// bottom right
path.lineTo(mid + half * 1.32, half * 1.45);
// top left
path.lineTo(mid + half * 0.5, half * 0.84);
return path;
}
@override
void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {
var mid = rect.width / 2;
var min = Math.min(rect.width, rect.height);
var half = min / 2;
mid = mid - half;
var path = Path();
// top left
path.moveTo(mid + half * 0.5, half * 0.84);
// top right
path.lineTo(mid + half * 1.5, half * 0.84);
// bottom left
path.lineTo(mid + half * 0.68, half * 1.45);
// top tip
path.lineTo(mid + half * 1.0, half * 0.5);
// bottom right
path.lineTo(mid + half * 1.32, half * 1.45);
// top left
path.lineTo(mid + half * 0.5, half * 0.84);
canvas.drawPath(
path,
Paint()..color = Colors.amber,
);
}
@override
ShapeBorder scale(double t) {
return this.scale(t);
}
}