在画布上绘制描边/有边框的文本



我正在尝试在画布上绘制描边文本。在我的编辑器中,我通过堆叠两个文本宽度创建了描边文本效果:

class TextDataView extends ElementView<TextData> {
final String placeholderText;
TextDataView(TextData data, {required this.placeholderText}) : super(data);
Text buildText(BuildContext context) {
return Text(
data.text.isNotEmpty ? data.text : placeholderText,
style: data.getTextStyle(),
textAlign: data.textAlignment,
);
}
@override
Widget build(BuildContext context) {
final text = buildText(context);
return Stack(
alignment: Alignment.center,
children: [
// for outline
Text(
text.data!,
style: text.style!.copyWith(
foreground: Paint()
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..strokeWidth = data.textStrokeSize
..color = data.textStrokeSize == 0
? Colors.transparent
: data.textStrokeColor,
color: null,
),
maxLines: text.maxLines,
overflow: text.overflow,
semanticsLabel: text.semanticsLabel,
softWrap: text.softWrap,
strutStyle: text.strutStyle,
textAlign: text.textAlign,
textDirection: text.textDirection,
textScaleFactor: text.textScaleFactor,
),
// for display
text,
],
);
}
}
对于输出渲染,我只能绘制显示文本:

extension TextDataToTextPainter on TextData {
TextPainter composeText() {
return TextPainter(
textAlign: textAlignment,
textDirection: textDirection,
maxLines: maxLines,
textScaleFactor: textScaleFactor,
text: TextSpan(
text: text,
style: getTextStyle(),
),
);
}
}

class EditorTextPainter extends ElementPainter<TransformData<TextData>> {
@override
Future<void> draw(Canvas canvas, Size size, TransformData<TextData> data) {
canvas.saveLayer(Offset.zero & size, Paint());
final text = data.data.composeText();
final offset = data.offset.alongSize(size);
final textSize = data.size.toActualSize(size);
text.layout(maxWidth: textSize.width);
text.paint(canvas, offset);
canvas.rotate(data.angle);
canvas.restore();
return Future.value();
}
}

如何用TextPainter画笔画呢?

我可以在显示文本之前绘制边框文本

最新更新