对于 colored颜色 混合2小工具,特别是如果我们想要将images或其他color texture与text混合,我们必须利用Flutter 画布的核心绘制功能来允许混合效果,就像在类似于CSS、SVG或Photoshop的应用程序中一样.
以下是一个完整的例子,基于this SO post个:
创建一个blendmask.dart文件并粘贴以下代码:
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
class BlendMask extends SingleChildRenderObjectWidget {
final BlendMode blendMode;
final double opacity;
BlendMask({
required this.blendMode,
this.opacity = 1.0,
Key? key,
Widget? child,
}) : super(key: key, child: child);
@override
RenderObject createRenderObject(context) {
return RenderBlendMask(blendMode, opacity);
}
@override
void updateRenderObject(BuildContext context, RenderBlendMask renderObject) {
renderObject.blendMode = blendMode;
renderObject.opacity = opacity;
}
}
class RenderBlendMask extends RenderProxyBox {
BlendMode blendMode;
double opacity;
RenderBlendMask(this.blendMode, this.opacity);
@override
void paint(context, offset) {
context.canvas.saveLayer(
offset & size,
Paint()
..blendMode = blendMode
..color = Color.fromARGB((opacity * 255).round(), 255, 255, 255));
super.paint(context, offset);
context.canvas.restore();
}
}
这是你的main.dart分:
import 'package:flutter/material.dart';
import 'blendmask.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Blend Color Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Title"),
),
body: SizedBox.expand(
child: Stack(
children: [
SizedBox.expand(
child: Image.network(
fit: BoxFit.cover,
"https://images.unsplash.com/photo-1620641788421-7a1c342ea42e?ixlib=rb-0.3.5&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA&s=a0c8d632e977f94e5d312d9893258f59&auto=format&fit=crop&w=1355&q=80"),
),
BlendMask(
opacity: 1.0,
blendMode: BlendMode.difference,
child: const SizedBox.expand(
child: Text(
"\n \n This is \n \t\t a Title ",
style: TextStyle(
fontSize: 100,
fontWeight: FontWeight.w600,
color: Color.fromARGB(255, 53, 250, 119),
),
),
),
),
],
),
),
);
}
}
这就是结果: 请注意,您可以更改为different color blend modes.