我目前正在开发一个 Flutter 项目,需要帮助为 slider 拇指创建自定义形状。我的应用程序中有一个常规 slider 和一个 RangeSlider,我想为它们自定义拇指的外观。 为了清楚地了解该问题,我附上了两个 slider 的屏幕截图:
我非常感谢任何有关如何在 Flutter 中为 slider 拇指创建自定义形状的指导、建议或代码示例。预先感谢您的帮助!
最佳答案
您可以通过扩展 SliderComponentShape 来创建自定义拇指形状并在 Slider 中使用它:
class AppSliderShape extends SliderComponentShape {
final double thumbRadius;
const AppSliderShape({required this.thumbRadius});
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return Size.fromRadius(thumbRadius);
}
@override
void paint(
PaintingContext context,
Offset center, {
required Animation<double> activationAnimation,
required Animation<double> enableAnimation,
required bool isDiscrete,
required TextPainter labelPainter,
required RenderBox parentBox,
required SliderThemeData sliderTheme,
required TextDirection textDirection,
required double value,
required double textScaleFactor,
required Size sizeWithOverflow,
}) {
final Canvas canvas = context.canvas;
final paint = Paint()
..style = PaintingStyle.fill
..color = Colors.white;
// draw icon with text painter
const iconData = Icons.drag_handle;
final TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(
text: String.fromCharCode(iconData.codePoint),
style: TextStyle(
fontSize: thumbRadius * 2,
fontFamily: iconData.fontFamily,
color: sliderTheme.thumbColor,
));
textPainter.layout();
final Offset textCenter = Offset(center.dx - (textPainter.width / 2),
center.dy - (textPainter.height / 2));
const cornerRadius = 4.0;
// draw the background shape here..
canvas.drawRRect(
RRect.fromRectXY(
Rect.fromCenter(center: center, width: 30, height: 20), cornerRadius, cornerRadius),
paint,
);
textPainter.paint(canvas, textCenter);
}
}
然后在你的 SliderTheme 中:
SliderTheme(
data: SliderThemeData(
thumbColor: Colors.teal,
thumbShape: AppSliderShape(thumbRadius: 10),
),
child: Slider(),
),
关于flutter - 在 Flutter 中为 Slider Thumb 创建自定义形状(Slider 和 RangeSlider),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76485032/