我们实现一个有趣的操作-通过点击按钮生成一个二维码弹窗然后组件截图,最好保存到相册
1.生成弹窗
1)准备基础的加载结构
注意:该弹窗结构必须使用@CustomDialog修饰且里面必须写控制器
示例代码如下(详细讲解已在代码中):
scss
@Entry
@Component
struct Index01 {
@State message: string = 'Hello World';
// 自定义分享弹窗控制器
dialog = new CustomDialogController({
builder: QRcodeDialog(),
customStyle: true,
alignment: DialogAlignment.Center
})
build() {
Column(){
Button('生成二维码')
.onClick(()=>{
this.dialog.open()
})
}
.width('100%')
.justifyContent(FlexAlign.Center)
}
}
// 定义一个名为 QRcodeDialog 的结构体,该弹窗必须使用@CustomDialog修饰
@CustomDialog
export struct QRcodeDialog {
// 定义一个成员变量 controller,类型为 CustomDialogController,用于控制对话框的行为(必须写)
controller: CustomDialogController
build() {
// 使用 Stack 布局,内容对齐方式为右下角对齐
Stack({ alignContent: Alignment.BottomEnd }) {
Column({ space: 20 }) {
Text('生成二维码弹窗')
// 在 Column 中添加一个分割线组件
Divider()
// 设置分割线的宽度为 1
.strokeWidth(1)
Text('弹窗如下' )
.fontSize(12)
.fontWeight(600)
.width('100%')
// 在 Column 中添加一个二维码组件,内容为 'share'(可自定义)
QRCode('share')
.width(160)
.height(160)
// 设置二维码在 Column 中的对齐方式为居中
.alignSelf(ItemAlign.Center)
Text('点击右下角保存该弹窗')
.fontSize(16)
// 在 Column 中添加一个空白组件,占满剩余空间
Blank()
}
.padding(20)
.width(300)
.height(500)
Row() {
Text('保存到本地')
.fontColor(Color.Blue)
.fontSize(14)
.padding(12)
.backgroundColor(Color.White)
}
}
// 设置 Stack 的边框圆角为 8
.borderRadius(8)
// 设置 Stack 的背景颜色为橙色
.backgroundColor(Color.Orange)
}
}
2.在该弹窗中生成二维码(该代码也已经写在上面示例中)
QRCode-信息展示-ArkTS组件-ArkUI(方舟UI框架)-应用框架 - 华为HarmonyOS开发者
这里给出具体示例代码:
scss
// 在 Column 中添加一个二维码组件,内容为 'share'
QRCode('share')
.width(160)
.height(160)
// 设置二维码在 Column 中的对齐方式为居中
.alignSelf(ItemAlign.Center)
QRCode的括号中随机写一个字符串等等,它将根据该字符串生成二维码,如果不写就报错
3.完成剩余步骤
重点:new CustomDialogController写出弹窗控制器,通过按钮和onclick实现出现二维码弹窗
最后完成的二维码弹窗如下:
编辑
该示例完整代码:
scss
@Entry
@Component
struct Index01 {
@State message: string = 'Hello World';
// 自定义弹窗控制器
dialog = new CustomDialogController({
builder: QRcodeDialog(),
customStyle: true,
alignment: DialogAlignment.Center
})
build() {
Column(){
Button('生成二维码')
.onClick(()=>{
this.dialog.open()
})
}
.width('100%')
.justifyContent(FlexAlign.Center)
}
}
// 定义一个名为 QRcodeDialog 的结构体,该弹窗必须使用@CustomDialog修饰
@CustomDialog
export struct QRcodeDialog {
// 定义一个成员变量 controller,类型为 CustomDialogController,用于控制对话框的行为(必须写)
controller: CustomDialogController
build() {
// 使用 Stack 布局,内容对齐方式为右下角对齐
Stack({ alignContent: Alignment.BottomEnd }) {
Column({ space: 20 }) {
Text('生成二维码弹窗')
// 在 Column 中添加一个分割线组件
Divider()
// 设置分割线的宽度为 1
.strokeWidth(1)
Text('弹窗如下' )
.fontSize(12)
.fontWeight(600)
.width('100%')
// 在 Column 中添加一个二维码组件,内容为 'share'(可自定义)
QRCode('share')
.width(160)
.height(160)
// 设置二维码在 Column 中的对齐方式为居中
.alignSelf(ItemAlign.Center)
Text('点击右下角保存该弹窗')
.fontSize(16)
// 在 Column 中添加一个空白组件,占满剩余空间
Blank()
}
.padding(20)
.width(300)
.height(500)
Row() {
Text('保存到本地')
.fontColor(Color.Blue)
.fontSize(14)
.padding(12)
.backgroundColor(Color.White)
}
}
// 设置 Stack 的边框圆角为 8
.borderRadius(8)
// 设置 Stack 的背景颜色为橙色
.backgroundColor(Color.Orange)
}
}
适用HarmonyOS NEXT / API12或以上版本