HarmonyOS 鸿蒙Next background(builder: CustomBuilder, options?: { align?: Alignment })示例,想看看builder: CustomBuilder如何实现背景色,这个在HarmonyOS 鸿蒙Next中能否实现动态背景色
HarmonyOS 鸿蒙Next background(builder: CustomBuilder, options?: { align?: Alignment })示例,想看看builder: CustomBuilder如何实现背景色,这个在HarmonyOS 鸿蒙Next中能否实现动态背景色
同上
7 回复
预览器不行,但是模拟器可以。
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Page10 {
build() {
Column() {
Text('hello word 123')
}
.width('100%')
.height('50%')
.background(overBuilder(),{align:Alignment.Bottom})
}
}
//全局自定义组件函数
@Builder function overBuilder() {
Page10Child()
}
@Component
struct Page10Child {
build() {
Column() {
Image($r(‘app.media.background’)).width(‘100%’).height(‘100%’)
}
.width(‘100%’)
.height(‘100%’)
}
}
预览器不行应该是应用没打包,访问不到资源文件,哈哈哈哈
可以在资源目录下放一张图片,overBuilder中引用该图片,测试可以看到图片变成了背景图,没测试overBuilder中写其他组件会发生什么,可以自己试一下
[@Entry](/user/Entry)
[@Component](/user/Component)
struct NewPage {
aboutToAppear() {
}
[@State](/user/State) message: string = 'Hello World'
[@State](/user/State) msg:string = '';
build() {
Column() {
Text('hello word')
}
.width('100%')
.height('100%')
.background(overBuilder)
}
}
[@Builder](/user/Builder) function overBuilder() {
Image($rawfile('image/xxx.jpg')).width('100%').height('100%')
}
非常感谢,但是感觉如果就这种功能感觉用处不大
我按照这样咋没用呐
在HarmonyOS 鸿蒙Next中,通过CustomBuilder
实现背景色,并使其支持动态背景色是可行的。CustomBuilder
是一个允许你自定义组件构建逻辑的接口。要实现动态背景色,你可以利用状态管理和组件重绘机制。
以下是一个基本示例框架,展示如何通过CustomBuilder
来设置和更新背景色:
import 'package:harmonyos_flutter/ui/components/custom_painter.dart';
class DynamicBackground extends StatefulWidget {
@override
_DynamicBackgroundState createState() => _DynamicBackgroundState();
}
class _DynamicBackgroundState extends State<DynamicBackground> {
Color _backgroundColor = Colors.white;
void changeBackgroundColor() {
setState(() {
_backgroundColor = Colors.blue; // 动态改变背景色
});
}
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: BackgroundPainter(_backgroundColor),
size: Size.infinite,
);
}
}
class BackgroundPainter extends CustomPainter {
Color color;
BackgroundPainter(this.color);
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()..color = color;
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return oldDelegate.color != color;
}
}
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html