未验证 提交 4e6108b1 编写于 作者: O openharmony_ci 提交者: Gitee

!23966 update api ui md

Merge pull request !23966 from 李欣楠/master
...@@ -585,7 +585,9 @@ getSystemFontList(): Array\<string> ...@@ -585,7 +585,9 @@ getSystemFontList(): Array\<string>
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let font:Font|undefined = uiContext.getFont(); let font:Font|undefined = uiContext.getFont();
font.getSystemFontList() if(font){
font.getSystemFontList()
}
``` ```
### getFontByName ### getFontByName
...@@ -613,7 +615,9 @@ getFontByName(fontName: string): font.FontInfo ...@@ -613,7 +615,9 @@ getFontByName(fontName: string): font.FontInfo
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let font:Font|undefined = uiContext.getFont(); let font:Font|undefined = uiContext.getFont();
font.getFontByName('Sans Italic') if(font){
font.getFontByName('Sans Italic')
}
``` ```
## ComponentUtils ## ComponentUtils
...@@ -753,7 +757,7 @@ pushUrl(options: router.RouterOptions): Promise&lt;void&gt; ...@@ -753,7 +757,7 @@ pushUrl(options: router.RouterOptions): Promise&lt;void&gt;
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base'; import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter(); let router:Router = uiContext.getRouter();
try { try {
router.pushUrl({ router.pushUrl({
url: 'pages/routerpage2', url: 'pages/routerpage2',
...@@ -801,7 +805,7 @@ pushUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): voi ...@@ -801,7 +805,7 @@ pushUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): voi
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base'; import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter(); let router:Router = uiContext.getRouter();
router.pushUrl({ router.pushUrl({
url: 'pages/routerpage2', url: 'pages/routerpage2',
params: { params: {
...@@ -970,7 +974,7 @@ replaceUrl(options: router.RouterOptions): Promise&lt;void&gt; ...@@ -970,7 +974,7 @@ replaceUrl(options: router.RouterOptions): Promise&lt;void&gt;
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base'; import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter(); let router:Router = uiContext.getRouter();
try { try {
router.replaceUrl({ router.replaceUrl({
url: 'pages/detail', url: 'pages/detail',
...@@ -1014,7 +1018,7 @@ replaceUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): ...@@ -1014,7 +1018,7 @@ replaceUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;):
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base'; import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter(); let router:Router = uiContext.getRouter();
router.replaceUrl({ router.replaceUrl({
url: 'pages/detail', url: 'pages/detail',
params: { params: {
...@@ -1173,7 +1177,7 @@ pushNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt; ...@@ -1173,7 +1177,7 @@ pushNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base'; import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter(); let router:Router = uiContext.getRouter();
try { try {
router.pushNamedRoute({ router.pushNamedRoute({
name: 'myPage', name: 'myPage',
...@@ -1221,7 +1225,7 @@ pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;vo ...@@ -1221,7 +1225,7 @@ pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;vo
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base'; import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter(); let router:Router = uiContext.getRouter();
router.pushNamedRoute({ router.pushNamedRoute({
name: 'myPage', name: 'myPage',
params: { params: {
...@@ -1389,7 +1393,7 @@ replaceNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt; ...@@ -1389,7 +1393,7 @@ replaceNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base'; import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter(); let router:Router = uiContext.getRouter();
try { try {
router.replaceNamedRoute({ router.replaceNamedRoute({
name: 'myPage', name: 'myPage',
...@@ -1433,7 +1437,7 @@ replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt ...@@ -1433,7 +1437,7 @@ replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt
```ts ```ts
import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base'; import { BusinessError } from '@ohos.base';
let router = uiContext.getRouter(); let router:Router = uiContext.getRouter();
router.replaceNamedRoute({ router.replaceNamedRoute({
name: 'myPage', name: 'myPage',
params: { params: {
......
...@@ -11,7 +11,13 @@ UI界面除了运行动画之外,还承载着与用户进行实时交互的功 ...@@ -11,7 +11,13 @@ UI界面除了运行动画之外,还承载着与用户进行实时交互的功
```ts ```ts
import curves from '@ohos.curves' import curves from '@ohos.curves'
class SetSlt{
scaleToggle:boolean = true
set():void{
this.scaleToggle = !this.scaleToggle;
}
}
let CurAn:Record<string,curves> = {'curve':curves.springMotion()}
// 第一步:声明相关状态变量 // 第一步:声明相关状态变量
@state scaleToggle: boolean = true; @state scaleToggle: boolean = true;
...@@ -25,9 +31,7 @@ Column() { ...@@ -25,9 +31,7 @@ Column() {
this.scaleToggle = !this.scaleToggle; this.scaleToggle = !this.scaleToggle;
}) })
// 第四步:通过隐式动画接口开启隐式动画,动画终点值改变时,系统自动添加衔接动画 // 第四步:通过隐式动画接口开启隐式动画,动画终点值改变时,系统自动添加衔接动画
.animation({ .animation(CurAn)
curve: curves.springMotion()
})
} }
... ...
``` ```
...@@ -37,7 +41,13 @@ Column() { ...@@ -37,7 +41,13 @@ Column() {
```ts ```ts
import curves from '@ohos.curves'; import curves from '@ohos.curves';
class SetSlt{
scaleToggle:boolean = true
set():void{
this.scaleToggle = !this.scaleToggle;
}
}
let CurAn:Record<string,curves> = {'curve':curves.springMotion()}
@Entry @Entry
@Component @Component
struct AnimationToAnimationDemo { struct AnimationToAnimationDemo {
...@@ -60,7 +70,8 @@ struct AnimationToAnimationDemo { ...@@ -60,7 +70,8 @@ struct AnimationToAnimationDemo {
Button('Click') Button('Click')
.margin({ top: 200 }) .margin({ top: 200 })
.onClick(() => { .onClick(() => {
this.isAnimation = !this.isAnimation; let sets = new SetSlt()
sets.set()
}) })
} }
.width('100%') .width('100%')
...@@ -85,7 +96,14 @@ struct AnimationToAnimationDemo { ...@@ -85,7 +96,14 @@ struct AnimationToAnimationDemo {
```ts ```ts
import curves from '@ohos.curves' import curves from '@ohos.curves'
class SetOffset{
offsetX:number = 0;
offsetY:number = 0;
set(x:number,y:number):void{
this.offsetX = x;
this.offsetY = y;
}
}
// 第一步:声明相关状态变量 // 第一步:声明相关状态变量
@state offsetX: number = 0; @state offsetX: number = 0;
@State offsetY: number = 0; @State offsetY: number = 0;
...@@ -97,13 +115,15 @@ Column() ...@@ -97,13 +115,15 @@ Column()
.translate({ x: this.offsetX, y: this.offsetY}) .translate({ x: this.offsetX, y: this.offsetY})
.gesture( .gesture(
PanGesture({}) PanGesture({})
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event?: GestureEvent) => {
// 第三步:在跟手过程改变状态变量值,并且采用reponsiveSpringMotion动画运动到新的值 // 第三步:在跟手过程改变状态变量值,并且采用reponsiveSpringMotion动画运动到新的值
animateTo({ animateTo({
curve: curves.responsiveSpringMotion() curve: curves.responsiveSpringMotion()
}, () => { }, () => {
this.offsetX = event.offsetX; if(event){
this.offsetY = event.offsetY; let setxy = new SetOffset();
setxy.set(event.offsetX,event.offsetY)
}
}) })
}) })
.onActionEnd(() => { .onActionEnd(() => {
...@@ -111,8 +131,8 @@ Column() ...@@ -111,8 +131,8 @@ Column()
animateTo({ animateTo({
curve: curves.SpringMotion() curve: curves.SpringMotion()
}, () => { }, () => {
this.offsetX = targetOffsetX; let setxy = new SetOffset();
this.offsetY = targetOffsetY; setxy.set(targetOffsetX,targetOffsetY)
}) })
}) })
) )
...@@ -124,7 +144,20 @@ Column() ...@@ -124,7 +144,20 @@ Column()
```ts ```ts
import curves from '@ohos.curves'; import curves from '@ohos.curves';
class SetOffset{
offsetX:number = 0;
offsetY:number = 0;
positionX:number = 100;
positionY:number = 100;
set(x:number,y:number):void{
this.offsetX = x;
this.offsetY = y;
}
setJ(x:number,y:number,diameter:number = 50):void{
this.positionX = x - diameter / 2;
this.positionY = y - diameter / 2;
}
}
@Entry @Entry
@Component @Component
struct SpringMotionDemo { struct SpringMotionDemo {
...@@ -138,23 +171,25 @@ struct SpringMotionDemo { ...@@ -138,23 +171,25 @@ struct SpringMotionDemo {
Circle({ width: this.diameter, height: this.diameter }) Circle({ width: this.diameter, height: this.diameter })
.fill(Color.Blue) .fill(Color.Blue)
.position({ x: this.positionX, y: this.positionY }) .position({ x: this.positionX, y: this.positionY })
.onTouch((event: TouchEvent) => { .onTouch((event?: TouchEvent) => {
if(event){
if (event.type === TouchType.Move) { if (event.type === TouchType.Move) {
// 跟手过程,使用responsiveSpringMotion曲线 // 跟手过程,使用responsiveSpringMotion曲线
animateTo({ curve: curves.responsiveSpringMotion() }, () => { animateTo({ curve: curves.responsiveSpringMotion() }, () => {
// 减去半径,以使球的中心运动到手指位置 // 减去半径,以使球的中心运动到手指位置
this.positionX = event.touches[0].screenX - this.diameter / 2; let setxy = new SetOffset();
this.positionY = event.touches[0].screenY - this.diameter / 2; setxy.setJ(event.touches[0].screenX,event.touches[0].screenY,this.diameter)
console.info(`move, animateTo x:${this.positionX}, y:${this.positionY}`); console.info(`move, animateTo x:${setxy.positionX}, y:${setxy.positionY}`);
}) })
} else if (event.type === TouchType.Up) { } else if (event.type === TouchType.Up) {
// 离手时,使用springMotion曲线 // 离手时,使用springMotion曲线
animateTo({ curve: curves.springMotion() }, () => { animateTo({ curve: curves.springMotion() }, () => {
this.positionX = 100; let setxy = new SetOffset();
this.positionY = 100; setxy.set(100,100)
console.info(`touchUp, animateTo x:100, y:100`); console.info(`touchUp, animateTo x:100, y:100`);
}) })
} }
}
}) })
} }
.width("100%").height("80%") .width("100%").height("80%")
......
...@@ -162,6 +162,9 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true }) ...@@ -162,6 +162,9 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true })
```ts ```ts
// xxx.ets // xxx.ets
import router from '@ohos.router'; import router from '@ohos.router';
let furl:Record<string,string> = {'url':'pages/first_page'}
let surl:Record<string,string> = {'url':'pages/second_page'}
let turl:Record<string,string> = {'url':'pages/third_page'}
@Entry @Entry
@Component @Component
struct ButtonCase1 { struct ButtonCase1 {
...@@ -169,19 +172,19 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true }) ...@@ -169,19 +172,19 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true })
List({ space: 4 }) { List({ space: 4 }) {
ListItem() { ListItem() {
Button("First").onClick(() => { Button("First").onClick(() => {
router.pushUrl({ url: 'pages/first_page' }) router.pushUrl(furl)
}) })
.width('100%') .width('100%')
} }
ListItem() { ListItem() {
Button("Second").onClick(() => { Button("Second").onClick(() => {
router.pushUrl({ url: 'pages/second_page' }) router.pushUrl(surl)
}) })
.width('100%') .width('100%')
} }
ListItem() { ListItem() {
Button("Third").onClick(() => { Button("Third").onClick(() => {
router.pushUrl({ url: 'pages/third_page' }) router.pushUrl(turl)
}) })
.width('100%') .width('100%')
} }
...@@ -232,13 +235,13 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true }) ...@@ -232,13 +235,13 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true })
build() { build() {
Stack() { Stack() {
List({ space: 20, initialIndex: 0 }) { List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item) => { ForEach(this.arr, (item:number) => {
ListItem() { ListItem() {
Text('' + item) Text('' + item)
.width('100%').height(100).fontSize(16) .width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
} }
}, item => item) }, ((item:number):number => item))
}.width('90%') }.width('90%')
Button() { Button() {
Image($r('app.media.ic_public_add')) Image($r('app.media.ic_public_add'))
......
...@@ -12,8 +12,8 @@ ...@@ -12,8 +12,8 @@
```ts ```ts
@CustomDialog @CustomDialog
struct CustomDialogExample { struct CustomDialogExample1 {
controller: CustomDialogController controller: CustomDialogController | undefined
build() { build() {
Column() { Column() {
Text('我是内容') Text('我是内容')
...@@ -27,18 +27,29 @@ ...@@ -27,18 +27,29 @@
3. 创建构造器,与装饰器呼应相连。 3. 创建构造器,与装饰器呼应相连。
```ts ```ts
dialogController: CustomDialogController = new CustomDialogController({ let bud:Record<string,string> = {}
builder: CustomDialogExample({}), let obj:object|undefined = undefined
dialogController: obj = new CustomDialogController({
builder: CustomDialogExample(bud),
}) })
``` ```
4. 点击与onClick事件绑定的组件使弹窗弹出 4. 点击与onClick事件绑定的组件使弹窗弹出
```ts ```ts
class dialogc{
dialogController:CustomDialogController|undefined = undefined
open(){
if(this.dialogController){
this.dialogController.open()
}
}
}
Flex({justifyContent:FlexAlign.Center}){ Flex({justifyContent:FlexAlign.Center}){
Button('click me') Button('click me')
.onClick(() => { .onClick(() => {
this.dialogController.open() let dia = new dialogc();
dia.open()
}) })
}.width('100%') }.width('100%')
``` ```
...@@ -54,24 +65,32 @@ ...@@ -54,24 +65,32 @@
1.\@CustomDialog装饰器内添加按钮操作,同时添加数据函数的创建。 1.\@CustomDialog装饰器内添加按钮操作,同时添加数据函数的创建。
```ts ```ts
class cancelconfirmF{
cancel():void{}
confirm():void{}
}
@CustomDialog @CustomDialog
struct CustomDialogExample { struct CustomDialogExample {
controller: CustomDialogController controller: CustomDialogController | undefined
cancel: () => void
confirm: () => void
build() { build() {
Column() { Column() {
Text('我是内容').fontSize(20).margin({ top: 10, bottom: 10 }) Text('我是内容').fontSize(20).margin({ top: 10, bottom: 10 })
Flex({ justifyContent: FlexAlign.SpaceAround }) { Flex({ justifyContent: FlexAlign.SpaceAround }) {
Button('cancel') Button('cancel')
.onClick(() => { .onClick(() => {
if(this.controller){
this.controller.close() this.controller.close()
this.cancel() }
let canf = new cancelconfirmF()
canf.cancel()
}).backgroundColor(0xffffff).fontColor(Color.Black) }).backgroundColor(0xffffff).fontColor(Color.Black)
Button('confirm') Button('confirm')
.onClick(() => { .onClick(() => {
if(this.controller){
this.controller.close() this.controller.close()
this.confirm() }
let conf = new cancelconfirmF()
conf.confirm()
}).backgroundColor(0xffffff).fontColor(Color.Red) }).backgroundColor(0xffffff).fontColor(Color.Red)
}.margin({ bottom: 10 }) }.margin({ bottom: 10 })
} }
...@@ -82,7 +101,7 @@ ...@@ -82,7 +101,7 @@
2. 页面内需要在构造器内进行接收,同时创建相应的函数操作。 2. 页面内需要在构造器内进行接收,同时创建相应的函数操作。
```ts ```ts
dialogController: CustomDialogController = new CustomDialogController({ dialogController: object = new CustomDialogController({
builder: CustomDialogExample({ builder: CustomDialogExample({
cancel: this.onCancel, cancel: this.onCancel,
confirm: this.onAccept, confirm: this.onAccept,
......
...@@ -68,7 +68,8 @@ struct RadioExample { ...@@ -68,7 +68,8 @@ struct RadioExample {
.onChange((isChecked: boolean) => { .onChange((isChecked: boolean) => {
if(isChecked) { if(isChecked) {
// 切换为响铃模式 // 切换为响铃模式
promptAction.showToast({ message: 'Ringing mode.' }) let st:Record<string,string> = {'message': 'Ringing mode.'}
promptAction.showToast(st)
} }
}) })
Text('Ringing') Text('Ringing')
...@@ -80,7 +81,8 @@ struct RadioExample { ...@@ -80,7 +81,8 @@ struct RadioExample {
.onChange((isChecked: boolean) => { .onChange((isChecked: boolean) => {
if(isChecked) { if(isChecked) {
// 切换为振动模式 // 切换为振动模式
promptAction.showToast({ message: 'Vibration mode.' }) let st:Record<string,string> = {'message': 'Vibration mode.'}
promptAction.showToast(st)
} }
}) })
Text('Vibration') Text('Vibration')
...@@ -92,7 +94,8 @@ struct RadioExample { ...@@ -92,7 +94,8 @@ struct RadioExample {
.onChange((isChecked: boolean) => { .onChange((isChecked: boolean) => {
if(isChecked) { if(isChecked) {
// 切换为静音模式 // 切换为静音模式
promptAction.showToast({ message: 'Silent mode.' }) let st:Record<string,string> = {'message': 'Silent mode.'}
promptAction.showToast(st)
} }
}) })
Text('Silent') Text('Silent')
......
...@@ -133,9 +133,11 @@ struct ToggleExample { ...@@ -133,9 +133,11 @@ struct ToggleExample {
.margin({left: 200, right: 10}) .margin({left: 200, right: 10})
.onChange((isOn: boolean) => { .onChange((isOn: boolean) => {
if(isOn) { if(isOn) {
promptAction.showToast({ message: 'Bluetooth is on.' }) let st:Record<string,string> = {'message': 'Bluetooth is on.'}
promptAction.showToast(st)
} else { } else {
promptAction.showToast({ message: 'Bluetooth is off.' }) let st:Record<string,string> = {'message': 'Bluetooth is off.'}
promptAction.showToast(st)
} }
}) })
} }
......
...@@ -34,7 +34,7 @@ Video组件支持加载本地视频和网络视频。 ...@@ -34,7 +34,7 @@ Video组件支持加载本地视频和网络视频。
```ts ```ts
@Component @Component
export struct VideoPlayer{ export struct VideoPlayer{
private controller:VideoController; private controller:VideoController | undefined;
private previewUris: Resource = $r ('app.media.preview'); private previewUris: Resource = $r ('app.media.preview');
private innerResource: Resource = $rawfile('videoTest.mp4'); private innerResource: Resource = $rawfile('videoTest.mp4');
build(){ build(){
...@@ -55,7 +55,7 @@ Video组件支持加载本地视频和网络视频。 ...@@ -55,7 +55,7 @@ Video组件支持加载本地视频和网络视频。
```ts ```ts
@Component @Component
export struct VideoPlayer{ export struct VideoPlayer{
private controller:VideoController; private controller:VideoController | undefined;
private previewUris: Resource = $r ('app.media.preview'); private previewUris: Resource = $r ('app.media.preview');
private videosrc: string= 'dataability://device_id/com.domainname.dataability.videodata/video/10' private videosrc: string= 'dataability://device_id/com.domainname.dataability.videodata/video/10'
build(){ build(){
...@@ -77,7 +77,7 @@ Video组件支持加载本地视频和网络视频。 ...@@ -77,7 +77,7 @@ Video组件支持加载本地视频和网络视频。
```ts ```ts
@Component @Component
export struct VideoPlayer { export struct VideoPlayer {
private controller: VideoController; private controller: VideoController | undefined;
private videosrc: string = 'file:///data/storage/el2/base/haps/entry/files/show.mp4' private videosrc: string = 'file:///data/storage/el2/base/haps/entry/files/show.mp4'
build() { build() {
...@@ -100,7 +100,7 @@ export struct VideoPlayer { ...@@ -100,7 +100,7 @@ export struct VideoPlayer {
```ts ```ts
@Component @Component
export struct VideoPlayer{ export struct VideoPlayer{
private controller:VideoController; private controller:VideoController | undefined;
private previewUris: Resource = $r ('app.media.preview'); private previewUris: Resource = $r ('app.media.preview');
private videosrc: string= 'https://www.example.com/example.mp4' // 使用时请替换为实际视频加载网址 private videosrc: string= 'https://www.example.com/example.mp4' // 使用时请替换为实际视频加载网址
build(){ build(){
...@@ -124,7 +124,7 @@ Video组件[属性](../reference/arkui-ts/ts-media-components-video.md#属性) ...@@ -124,7 +124,7 @@ Video组件[属性](../reference/arkui-ts/ts-media-components-video.md#属性)
```ts ```ts
@Component @Component
export struct VideoPlayer { export struct VideoPlayer {
private controller: VideoController; private controller: VideoController | undefined;
build() { build() {
Column() { Column() {
...@@ -150,7 +150,7 @@ export struct VideoPlayer { ...@@ -150,7 +150,7 @@ export struct VideoPlayer {
@Entry @Entry
@Component @Component
struct VideoPlayer{ struct VideoPlayer{
private controller:VideoController; private controller:VideoController | undefined;
private previewUris: Resource = $r ('app.media.preview'); private previewUris: Resource = $r ('app.media.preview');
private innerResource: Resource = $rawfile('videoTest.mp4'); private innerResource: Resource = $rawfile('videoTest.mp4');
build(){ build(){
...@@ -213,7 +213,7 @@ Video控制器主要用于控制视频的状态,包括播放、暂停、停止 ...@@ -213,7 +213,7 @@ Video控制器主要用于控制视频的状态,包括播放、暂停、停止
```ts ```ts
@Entry @Entry
@Component @Component
struct VideoGuide { struct VideoGuide1 {
@State videoSrc: Resource = $rawfile('videoTest.mp4') @State videoSrc: Resource = $rawfile('videoTest.mp4')
@State previewUri: string = 'common/videoIcon.png' @State previewUri: string = 'common/videoIcon.png'
@State curRate: PlaybackSpeed = PlaybackSpeed.Speed_Forward_1_00_X @State curRate: PlaybackSpeed = PlaybackSpeed.Speed_Forward_1_00_X
...@@ -235,10 +235,14 @@ Video控制器主要用于控制视频的状态,包括播放、暂停、停止 ...@@ -235,10 +235,14 @@ Video控制器主要用于控制视频的状态,包括播放、暂停、停止
controller: this.controller controller: this.controller
}).controls(false).autoPlay(true) }).controls(false).autoPlay(true)
.onPrepared((event)=>{ .onPrepared((event)=>{
if(event){
this.durationTime = event.duration this.durationTime = event.duration
}
}) })
.onUpdate((event)=>{ .onUpdate((event)=>{
if(event){
this.currentTime =event.time this.currentTime =event.time
}
}) })
Row() { Row() {
Text(JSON.stringify(this.currentTime) + 's') Text(JSON.stringify(this.currentTime) + 's')
......
...@@ -229,11 +229,19 @@ OpenHarmony上Camera、AVPlayer等符合生产者设计的部件都可以将数 ...@@ -229,11 +229,19 @@ OpenHarmony上Camera、AVPlayer等符合生产者设计的部件都可以将数
```ts ```ts
class suf{
surfaceId:string = "";
mXComponentController: XComponentController = new XComponentController();
set(){
this.surfaceId = this.mXComponentController.getXComponentSurfaceId()
}
}
@State surfaceId:string = ""; @State surfaceId:string = "";
mXComponentController: XComponentController = new XComponentController(); mXComponentController: object = new XComponentController();
XComponent({ id: '', type: 'surface', controller: this.mXComponentController }) XComponent({ id: '', type: 'surface', controller: this.mXComponentController })
.onLoad(() => { .onLoad(() => {
this.surfaceId = this.mXComponentController.getXComponentSurfaceId() let sufset = new suf()
sufset.set()
}) })
``` ```
......
...@@ -70,8 +70,10 @@ struct MouseExample { ...@@ -70,8 +70,10 @@ struct MouseExample {
Button(this.isHovered ? 'Hovered!' : 'Not Hover') Button(this.isHovered ? 'Hovered!' : 'Not Hover')
.width(200).height(100) .width(200).height(100)
.backgroundColor(this.isHovered ? Color.Green : Color.Gray) .backgroundColor(this.isHovered ? Color.Green : Color.Gray)
.onHover((isHover: boolean) => { // 使用onHover接口监听鼠标是否悬浮在Button组件上 .onHover((isHover?: boolean) => { // 使用onHover接口监听鼠标是否悬浮在Button组件上
if(isHover){
this.isHovered = isHover; this.isHovered = isHover;
}
}) })
}.width('100%').height('100%').justifyContent(FlexAlign.Center) }.width('100%').height('100%').justifyContent(FlexAlign.Center)
} }
...@@ -126,15 +128,19 @@ struct MouseExample { ...@@ -126,15 +128,19 @@ struct MouseExample {
.width(200) .width(200)
.height(100) .height(100)
.backgroundColor(this.isHovered ? Color.Green : Color.Gray) .backgroundColor(this.isHovered ? Color.Green : Color.Gray)
.onHover((isHover: boolean) => { .onHover((isHover?: boolean) => {
if(isHover){
this.isHovered = isHover this.isHovered = isHover
}
}) })
.onMouse((event: MouseEvent) => { // 给Button组件设置onMouse回调 .onMouse((event?: MouseEvent) => { // 设置Button的onMouse回调
if(event){
this.buttonText = 'Button onMouse:\n' + '' + this.buttonText = 'Button onMouse:\n' + '' +
'button = ' + event.button + '\n' + 'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' + 'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' + 'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')'; 'windowXY=(' + event.windowX + ',' + event.windowY + ')';
}
}) })
Divider() Divider()
Text(this.buttonText).fontColor(Color.Green) Text(this.buttonText).fontColor(Color.Green)
...@@ -146,12 +152,14 @@ struct MouseExample { ...@@ -146,12 +152,14 @@ struct MouseExample {
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
.borderWidth(2) .borderWidth(2)
.borderColor(Color.Red) .borderColor(Color.Red)
.onMouse((event: MouseEvent) => { // 给Column组件设置onMouse回调 .onMouse((event?: MouseEvent) => { // Set the onMouse callback for the column.
if(event){
this.columnText = 'Column onMouse:\n' + '' + this.columnText = 'Column onMouse:\n' + '' +
'button = ' + event.button + '\n' + 'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' + 'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' + 'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')'; 'windowXY=(' + event.windowX + ',' + event.windowY + ')';
}
}) })
} }
} }
...@@ -177,20 +185,40 @@ struct MouseExample { ...@@ -177,20 +185,40 @@ struct MouseExample {
```ts ```ts
class ish{
isHovered:boolean = false
set(val:boolean){
this.isHovered = val;
}
}
class butf{
buttonText:string = ''
set(val:string){
this.buttonText = val
}
}
Button(this.isHovered ? 'Hovered!' : 'Not Hover') Button(this.isHovered ? 'Hovered!' : 'Not Hover')
.width(200) .width(200)
.height(100) .height(100)
.backgroundColor(this.isHovered ? Color.Green : Color.Gray) .backgroundColor(this.isHovered ? Color.Green : Color.Gray)
.onHover((isHover: boolean) => { .onHover((isHover?: boolean) => {
this.isHovered = isHover; if(isHover){
let ishset = new ish()
ishset.set(isHover)
}
}) })
.onMouse((event: MouseEvent) => { .onMouse((event?: MouseEvent) => {
if(event){
if(event.stopPropagation){
event.stopPropagation(); // 在Button的onMouse事件中设置阻止冒泡 event.stopPropagation(); // 在Button的onMouse事件中设置阻止冒泡
this.buttonText = 'Button onMouse:\n' + '' + }
let butset = new butf()
butset.set('Button onMouse:\n' + '' +
'button = ' + event.button + '\n' + 'button = ' + event.button + '\n' +
'action = ' + event.action + '\n' + 'action = ' + event.action + '\n' +
'x,y = (' + event.x + ',' + event.y + ')' + '\n' + 'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
'windowXY=(' + event.windowX + ',' + event.windowY + ')'; 'windowXY=(' + event.windowX + ',' + event.windowY + ')');
}
}) })
``` ```
...@@ -298,7 +326,8 @@ struct KeyEventExample { ...@@ -298,7 +326,8 @@ struct KeyEventExample {
Column() { Column() {
Button('onKeyEvent') Button('onKeyEvent')
.width(140).height(70) .width(140).height(70)
.onKeyEvent((event: KeyEvent) => { // 给Button设置onKeyEvent事件 .onKeyEvent((event?: KeyEvent) => { // 给Button设置onKeyEvent事件
if(event){
if (event.type === KeyType.Down) { if (event.type === KeyType.Down) {
this.buttonType = 'Down'; this.buttonType = 'Down';
} }
...@@ -309,6 +338,7 @@ struct KeyEventExample { ...@@ -309,6 +338,7 @@ struct KeyEventExample {
'KeyType:' + this.buttonType + '\n' + 'KeyType:' + this.buttonType + '\n' +
'KeyCode:' + event.keyCode + '\n' + 'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText; 'KeyText:' + event.keyText;
}
}) })
Divider() Divider()
...@@ -317,7 +347,8 @@ struct KeyEventExample { ...@@ -317,7 +347,8 @@ struct KeyEventExample {
Divider() Divider()
Text(this.columnText).fontColor(Color.Red) Text(this.columnText).fontColor(Color.Red)
}.width('100%').height('100%').justifyContent(FlexAlign.Center) }.width('100%').height('100%').justifyContent(FlexAlign.Center)
.onKeyEvent((event: KeyEvent) => { // 给父组件Column设置onKeyEvent事件 .onKeyEvent((event?: KeyEvent) => { // 给父组件Column设置onKeyEvent事件
if(event){
if (event.type === KeyType.Down) { if (event.type === KeyType.Down) {
this.columnType = 'Down'; this.columnType = 'Down';
} }
...@@ -328,6 +359,7 @@ struct KeyEventExample { ...@@ -328,6 +359,7 @@ struct KeyEventExample {
'KeyType:' + this.buttonType + '\n' + 'KeyType:' + this.buttonType + '\n' +
'KeyCode:' + event.keyCode + '\n' + 'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText; 'KeyText:' + event.keyText;
}
}) })
} }
} }
...@@ -353,21 +385,36 @@ struct KeyEventExample { ...@@ -353,21 +385,36 @@ struct KeyEventExample {
```ts ```ts
class butypef{
buttonType:string = ''
set(val:string){
this.buttonType = val
}
get(){
return this.buttonType
}
}
Button('onKeyEvent') Button('onKeyEvent')
.width(140).height(70) .width(140).height(70)
.onKeyEvent((event: KeyEvent) => { .onKeyEvent((event?: KeyEvent|object) => {
// 通过stopPropagation阻止事件冒泡 // 通过stopPropagation阻止事件冒泡
if(event){
event.stopPropagation(); event.stopPropagation();
if (event.type === KeyType.Down) { if (event.type === KeyType.Down) {
this.buttonType = 'Down'; let butset = new butypef()
butset.set('Down')
} }
if (event.type === KeyType.Up) { if (event.type === KeyType.Up) {
this.buttonType = 'Up'; let butset = new butypef()
butset.set('Up')
} }
this.buttonText = 'Button: \n' + let butfset = new butf()
'KeyType:' + this.buttonType + '\n' + let butset = new butypef()
butfset.set('Button: \n' +
'KeyType:' + butset.get() + '\n' +
'KeyCode:' + event.keyCode + '\n' + 'KeyCode:' + event.keyCode + '\n' +
'KeyText:' + event.keyText; 'KeyText:' + event.keyText)
}
}) })
``` ```
......
...@@ -75,6 +75,8 @@ ...@@ -75,6 +75,8 @@
```ts ```ts
import List from '@ohos.util.List';
import promptAction from '@ohos.promptAction';
onFocus(event: () => void) onFocus(event: () => void)
``` ```
...@@ -345,9 +347,11 @@ struct FocusableExample { ...@@ -345,9 +347,11 @@ struct FocusableExample {
Divider() Divider()
}.width('100%').justifyContent(FlexAlign.Center) }.width('100%').justifyContent(FlexAlign.Center)
.onKeyEvent((e) => { // 绑定onKeyEvent,在该Column组件获焦时,按下'F'键,可将第二个Text的focusable置反 .onKeyEvent((e) => { // 绑定onKeyEvent,在该Column组件获焦时,按下'F'键,可将第二个Text的focusable置反
if(e){
if (e.keyCode === 2022 && e.type === KeyType.Down) { if (e.keyCode === 2022 && e.type === KeyType.Down) {
this.textFocusable = !this.textFocusable; this.textFocusable = !this.textFocusable;
} }
}
}) })
} }
} }
...@@ -401,7 +405,7 @@ import promptAction from '@ohos.promptAction'; ...@@ -401,7 +405,7 @@ import promptAction from '@ohos.promptAction';
class MyDataSource implements IDataSource { class MyDataSource implements IDataSource {
private list: number[] = []; private list: number[] = [];
private listener: DataChangeListener; private listener: DataChangeListener|undefined = undefined;
constructor(list: number[]) { constructor(list: number[]) {
this.list = list; this.list = list;
...@@ -411,7 +415,7 @@ class MyDataSource implements IDataSource { ...@@ -411,7 +415,7 @@ class MyDataSource implements IDataSource {
return this.list.length; return this.list.length;
} }
getData(index: number): any { getData(index: number): object {
return this.list[index]; return this.list[index];
} }
...@@ -423,16 +427,22 @@ class MyDataSource implements IDataSource { ...@@ -423,16 +427,22 @@ class MyDataSource implements IDataSource {
} }
} }
class TmpM{
left:number = 20
bottom:number = 20
right:number = 20
}
let MarginTmp:TmpM = new TmpM()
@Entry @Entry
@Component @Component
struct SwiperExample { struct SwiperExample {
private swiperController: SwiperController = new SwiperController() private swiperController: object = new SwiperController()
private data: MyDataSource = new MyDataSource([]) private data: object = new MyDataSource([])
aboutToAppear(): void { aboutToAppear(): void {
let list = [] let list:number[] = []
for (let i = 1; i <= 4; i++) { for (let i = 1; i <= 4; i++) {
list.push(i.toString()); list.push(i);
} }
this.data = new MyDataSource(list); this.data = new MyDataSource(list);
} }
...@@ -507,7 +517,7 @@ struct SwiperExample { ...@@ -507,7 +517,7 @@ struct SwiperExample {
.borderWidth(2) .borderWidth(2)
.borderColor(Color.Gray) .borderColor(Color.Gray)
.backgroundColor(Color.White) .backgroundColor(Color.White)
}, item => item) }, ((item:string):string => item))
} }
.cachedCount(2) .cachedCount(2)
.index(0) .index(0)
...@@ -522,6 +532,18 @@ struct SwiperExample { ...@@ -522,6 +532,18 @@ struct SwiperExample {
}) })
.margin({ left: 20, top: 20, right: 20 }) .margin({ left: 20, top: 20, right: 20 })
class swcf{
swiperController:SwiperController|undefined
fun(index:number){
if(this.swiperController){
if(index==0){
this.swiperController.showPrevious();
}else{
this.swiperController.showNext();
}
}
}
}
Row({ space: 40 }) { Row({ space: 40 }) {
Button('') Button('')
.fontSize(40) .fontSize(40)
...@@ -529,7 +551,8 @@ struct SwiperExample { ...@@ -529,7 +551,8 @@ struct SwiperExample {
.fontColor(Color.Black) .fontColor(Color.Black)
.backgroundColor(Color.Transparent) .backgroundColor(Color.Transparent)
.onClick(() => { .onClick(() => {
this.swiperController.showPrevious(); let swf = new swcf()
swf.fun(0)
}) })
Button('') Button('')
.fontSize(40) .fontSize(40)
...@@ -537,7 +560,8 @@ struct SwiperExample { ...@@ -537,7 +560,8 @@ struct SwiperExample {
.fontColor(Color.Black) .fontColor(Color.Black)
.backgroundColor(Color.Transparent) .backgroundColor(Color.Transparent)
.onClick(() => { .onClick(() => {
this.swiperController.showNext(); let swf = new swcf()
swf.fun(1)
}) })
} }
.width(480) .width(480)
...@@ -556,6 +580,7 @@ struct SwiperExample { ...@@ -556,6 +580,7 @@ struct SwiperExample {
.height(50) .height(50)
.backgroundColor('#dadbd9') .backgroundColor('#dadbd9')
let tmp:Record<string,string> = {'message':'Button OK on clicked'}
Button('OK') Button('OK')
.fontSize(30) .fontSize(30)
.fontColor('#787878') .fontColor('#787878')
...@@ -564,7 +589,7 @@ struct SwiperExample { ...@@ -564,7 +589,7 @@ struct SwiperExample {
.height(50) .height(50)
.backgroundColor('#dadbd9') .backgroundColor('#dadbd9')
.onClick(() => { .onClick(() => {
promptAction.showToast({ message: 'Button OK on clicked' }); promptAction.showToast(tmp);
}) })
} }
.width(480) .width(480)
...@@ -573,7 +598,7 @@ struct SwiperExample { ...@@ -573,7 +598,7 @@ struct SwiperExample {
.borderWidth(2) .borderWidth(2)
.borderColor(Color.Gray) .borderColor(Color.Gray)
.backgroundColor('#dff2e4') .backgroundColor('#dff2e4')
.margin({ left: 20, bottom: 20, right: 20 }) .margin(MarginTmp)
}.backgroundColor('#f2f2f2') }.backgroundColor('#f2f2f2')
.margin({ left: 50, top: 50, right: 20 }) .margin({ left: 50, top: 50, right: 20 })
} }
...@@ -592,6 +617,8 @@ struct SwiperExample { ...@@ -592,6 +617,8 @@ struct SwiperExample {
```ts ```ts
import promptAction from '@ohos.promptAction';
let Tmp:Record<string,string> = {'message':'Button OK on clicked'}
Button('OK') Button('OK')
.defaultFocus(true) // 设置Button-OK为defaultFocus .defaultFocus(true) // 设置Button-OK为defaultFocus
.fontSize(30) .fontSize(30)
...@@ -599,7 +626,7 @@ Button('OK') ...@@ -599,7 +626,7 @@ Button('OK')
.type(ButtonType.Normal) .type(ButtonType.Normal)
.width(140).height(50).backgroundColor('#dadbd9') .width(140).height(50).backgroundColor('#dadbd9')
.onClick(() => { .onClick(() => {
promptAction.showToast({ message: 'Button OK on clicked' }); promptAction.showToast(Tmp);
}) })
``` ```
...@@ -646,13 +673,22 @@ tabIndex用于设置自定义TAB键走焦顺序,默认值为0。使用“TAB/S ...@@ -646,13 +673,22 @@ tabIndex用于设置自定义TAB键走焦顺序,默认值为0。使用“TAB/S
```ts ```ts
class swcf{
swiperController:SwiperController|undefined
fun(){
if(this.swiperController){
this.swiperController.showPrevious();
}
}
}
Button('') Button('')
.fontSize(40) .fontSize(40)
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
.fontColor(Color.Black) .fontColor(Color.Black)
.backgroundColor(Color.Transparent) .backgroundColor(Color.Transparent)
.onClick(() => { .onClick(() => {
this.swiperController.showPrevious(); let swf = new swcf()
swf.fun()
}) })
.tabIndex(2) // Button-左箭头设置为第二个tabIndex节点 .tabIndex(2) // Button-左箭头设置为第二个tabIndex节点
``` ```
...@@ -660,13 +696,15 @@ tabIndex用于设置自定义TAB键走焦顺序,默认值为0。使用“TAB/S ...@@ -660,13 +696,15 @@ tabIndex用于设置自定义TAB键走焦顺序,默认值为0。使用“TAB/S
```ts ```ts
import promptAction from '@ohos.promptAction';
let Tmp:Record<string,string> = {'message':'Button OK on clicked'}
Button('OK') Button('OK')
.fontSize(30) .fontSize(30)
.fontColor('#787878') .fontColor('#787878')
.type(ButtonType.Normal) .type(ButtonType.Normal)
.width(140).height(50).backgroundColor('#dadbd9') .width(140).height(50).backgroundColor('#dadbd9')
.onClick(() => { .onClick(() => {
promptAction.showToast({ message: 'Button OK on clicked' }); promptAction.showToast(Tmp);
}) })
.tabIndex(3) // Button-OK设置为第三个tabIndex节点 .tabIndex(3) // Button-OK设置为第三个tabIndex节点
``` ```
...@@ -707,7 +745,7 @@ import promptAction from '@ohos.promptAction'; ...@@ -707,7 +745,7 @@ import promptAction from '@ohos.promptAction';
class MyDataSource implements IDataSource { class MyDataSource implements IDataSource {
private list: number[] = []; private list: number[] = [];
private listener: DataChangeListener; private listener: DataChangeListener|undefined = undefined;
constructor(list: number[]) { constructor(list: number[]) {
this.list = list; this.list = list;
...@@ -717,7 +755,7 @@ class MyDataSource implements IDataSource { ...@@ -717,7 +755,7 @@ class MyDataSource implements IDataSource {
return this.list.length; return this.list.length;
} }
getData(index: number): any { getData(index: number): number[] {
return this.list[index]; return this.list[index];
} }
...@@ -736,9 +774,9 @@ struct SwiperExample { ...@@ -736,9 +774,9 @@ struct SwiperExample {
private data: MyDataSource = new MyDataSource([]) private data: MyDataSource = new MyDataSource([])
aboutToAppear(): void { aboutToAppear(): void {
let list = [] let list: number[] = []
for (let i = 1; i <= 4; i++) { for (let i = 1; i <= 4; i++) {
list.push(i.toString()); list.push(i);
} }
this.data = new MyDataSource(list); this.data = new MyDataSource(list);
} }
...@@ -815,7 +853,7 @@ struct SwiperExample { ...@@ -815,7 +853,7 @@ struct SwiperExample {
.borderColor(Color.Gray) .borderColor(Color.Gray)
.backgroundColor(Color.White) .backgroundColor(Color.White)
.tabIndex(1) .tabIndex(1)
}, item => item) }, ((item:string):string => item))
} }
.cachedCount(2) .cachedCount(2)
.index(0) .index(0)
...@@ -866,6 +904,7 @@ struct SwiperExample { ...@@ -866,6 +904,7 @@ struct SwiperExample {
.height(50) .height(50)
.backgroundColor('#dadbd9') .backgroundColor('#dadbd9')
let tmp:Record<string,string> = {'message':'Button OK on clicked'}
Button('OK') Button('OK')
.fontSize(30) .fontSize(30)
.fontColor('#787878') .fontColor('#787878')
...@@ -875,7 +914,7 @@ struct SwiperExample { ...@@ -875,7 +914,7 @@ struct SwiperExample {
.backgroundColor('#dadbd9') .backgroundColor('#dadbd9')
.defaultFocus(true) .defaultFocus(true)
.onClick(() => { .onClick(() => {
promptAction.showToast({ message: 'Button OK on clicked' }); promptAction.showToast(tmp);
}) })
.groupDefaultFocus(true) // 设置Button-OK为第三个tabIndex节点的默认焦点 .groupDefaultFocus(true) // 设置Button-OK为第三个tabIndex节点的默认焦点
} }
...@@ -1017,6 +1056,7 @@ struct RequestFocusExample { ...@@ -1017,6 +1056,7 @@ struct RequestFocusExample {
} }
}.width('100%').margin({ top:20 }) }.width('100%').margin({ top:20 })
.onKeyEvent((e) => { .onKeyEvent((e) => {
if(e){
if (e.keyCode >= 2017 && e.keyCode <= 2022) { if (e.keyCode >= 2017 && e.keyCode <= 2022) {
this.requestId = e.keyCode - 2017; this.requestId = e.keyCode - 2017;
} else if (e.keyCode === 2030) { } else if (e.keyCode === 2030) {
...@@ -1027,11 +1067,14 @@ struct RequestFocusExample { ...@@ -1027,11 +1067,14 @@ struct RequestFocusExample {
if (e.type !== KeyType.Down) { if (e.type !== KeyType.Down) {
return; return;
} }
}
let res = focusControl.requestFocus(this.idList[this.requestId]); let res = focusControl.requestFocus(this.idList[this.requestId]);
let tmps:Record<string,string> = {'message':'Request success'}
let tmpf:Record<string,string> = {'message':'Request failed'}
if (res) { if (res) {
promptAction.showToast({message: 'Request success'}); promptAction.showToast(tmps);
} else { } else {
promptAction.showToast({message: 'Request failed'}); promptAction.showToast(tmpf);
} }
}) })
} }
......
...@@ -88,7 +88,7 @@ import image from '@ohos.multimedia.image'; ...@@ -88,7 +88,7 @@ import image from '@ohos.multimedia.image';
@Component @Component
struct Index { struct Index {
@State visible: Visibility = Visibility.Visible @State visible: Visibility = Visibility.Visible
private pixelMapReader = undefined private pixelMapReader:object|undefined = undefined
aboutToAppear() { aboutToAppear() {
console.info('begin to create pixmap has info message: ') console.info('begin to create pixmap has info message: ')
...@@ -97,21 +97,28 @@ struct Index { ...@@ -97,21 +97,28 @@ struct Index {
createPixelMap() { createPixelMap() {
let color = new ArrayBuffer(4 * 96 * 96); let color = new ArrayBuffer(4 * 96 * 96);
var buffer = new Uint8Array(color); let buffer = new Uint8Array(color);
for (var i = 0; i < buffer.length; i++) { for (let i = 0; i < buffer.length; i++) {
buffer[i] = (i + 1) % 255; buffer[i] = (i + 1) % 255;
} }
let opts = { class hw{
alphaType: 0, height:number = 96
editable: true, width:number = 96
pixelFormat: 4,
scaleMode: 1,
size: { height: 96, width: 96 }
} }
const promise = image.createPixelMap(color, opts); let hwo:hw = new hw()
promise.then((data) => { let opts:Record<string,number|boolean|hw> = {
'alphaType': 0,
'editable': true,
'pixelFormat': 4,
'scaleMode': 1,
'size': hwo
}
const promise:image = image.createPixelMap(color, opts);
promise.then((data:object|undefined) => {
console.info('create pixmap has info message: ' + JSON.stringify(data)) console.info('create pixmap has info message: ' + JSON.stringify(data))
if(data){
this.pixelMapReader = data; this.pixelMapReader = data;
}
}) })
} }
...@@ -148,7 +155,7 @@ struct Index { ...@@ -148,7 +155,7 @@ struct Index {
console.info('Text onDrag start') console.info('Text onDrag start')
return { pixelMap: this.pixelMapReader, extraInfo: 'custom extra info.' } return { pixelMap: this.pixelMapReader, extraInfo: 'custom extra info.' }
}) })
.onDrop((event: DragEvent, extraParams: string) => { .onDrop((event: DragEvent|undefined, extraParams: string|undefined) => {
console.info('Text onDragDrop, ') console.info('Text onDragDrop, ')
this.visible = Visibility.None //拖动结束后,使源不可见 this.visible = Visibility.None //拖动结束后,使源不可见
}) })
...@@ -190,7 +197,7 @@ struct Index { ...@@ -190,7 +197,7 @@ struct Index {
.visibility(Visibility.Visible) .visibility(Visibility.Visible)
List({ space: 20, initialIndex: 0 }) { List({ space: 20, initialIndex: 0 }) {
ForEach(this.number, (item) => { ForEach(this.number, (item:string) => {
ListItem() { ListItem() {
Text('' + item) Text('' + item)
.width('100%') .width('100%')
...@@ -200,7 +207,7 @@ struct Index { ...@@ -200,7 +207,7 @@ struct Index {
.textAlign(TextAlign.Center) .textAlign(TextAlign.Center)
.backgroundColor(0xFFFFFF) .backgroundColor(0xFFFFFF)
} }
}, item => item) }, ((item:string):string => item))
ListItem() { ListItem() {
Text('Across Window Drag This') Text('Across Window Drag This')
...@@ -217,16 +224,16 @@ struct Index { ...@@ -217,16 +224,16 @@ struct Index {
.width('90%') .width('90%')
.border({ width: 1 }) .border({ width: 1 })
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 })
.onDragEnter((event: DragEvent, extraParams: string) => { //拖拽进去组件 .onDragEnter((event: DragEvent|undefined, extraParams: string|undefined) => { //拖拽进去组件
console.info('List onDragEnter, ' + extraParams) console.info('List onDragEnter, ' + extraParams)
}) })
.onDragMove((event: DragEvent, extraParams: string) => { //拖拽时移动 .onDragMove((event: DragEvent|undefined, extraParams: string|undefined) => { //拖拽时移动
console.info('List onDragMove, ' + extraParams) console.info('List onDragMove, ' + extraParams)
}) })
.onDragLeave((event: DragEvent, extraParams: string) => { //拖拽离开组件 .onDragLeave((event: DragEvent|undefined, extraParams: string|undefined) => { //拖拽离开组件
console.info('List onDragLeave, ' + extraParams) console.info('List onDragLeave, ' + extraParams)
}) })
.onDrop((event: DragEvent, extraParams: string) => { //释放组件 .onDrop((event: DragEvent|undefined, extraParams: string|undefined) => { //释放组件
console.info('List onDragDrop, ' + extraParams) console.info('List onDragDrop, ' + extraParams)
this.visible2 = Visibility.Visible //拖拽完成使拖入目标可见 this.visible2 = Visibility.Visible //拖拽完成使拖入目标可见
}) })
...@@ -267,7 +274,8 @@ struct TouchExample { ...@@ -267,7 +274,8 @@ struct TouchExample {
build() { build() {
Column() { Column() {
Button('Touch').height(40).width(100) Button('Touch').height(40).width(100)
.onTouch((event: TouchEvent) => { .onTouch((event?: TouchEvent) => {
if(event){
if (event.type === TouchType.Down) { if (event.type === TouchType.Down) {
this.eventType = 'Down'; this.eventType = 'Down';
} }
...@@ -281,9 +289,11 @@ struct TouchExample { ...@@ -281,9 +289,11 @@ struct TouchExample {
+ event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:(' + event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:' + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height + event.target.area.width + '\nheight:' + event.target.area.height
}
}) })
Button('Touch').height(50).width(200).margin(20) Button('Touch').height(50).width(200).margin(20)
.onTouch((event: TouchEvent) => { .onTouch((event?: TouchEvent) => {
if(event){
if (event.type === TouchType.Down) { if (event.type === TouchType.Down) {
this.eventType = 'Down'; this.eventType = 'Down';
} }
...@@ -297,6 +307,7 @@ struct TouchExample { ...@@ -297,6 +307,7 @@ struct TouchExample {
+ event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:(' + event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:' + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height + event.target.area.width + '\nheight:' + event.target.area.height
}
}) })
Text(this.text) Text(this.text)
}.width('100%').padding(30) }.width('100%').padding(30)
......
...@@ -64,18 +64,21 @@ import curves from '@ohos.curves'; ...@@ -64,18 +64,21 @@ import curves from '@ohos.curves';
import window from '@ohos.window'; import window from '@ohos.window';
import display from '@ohos.display'; import display from '@ohos.display';
import mediaquery from '@ohos.mediaquery'; import mediaquery from '@ohos.mediaquery';
export class GlobalContext {
static mainWin: window.Window|undefined = undefined;
static mainWindowSize:window.Size|undefined = undefined;
}
/** /**
* 窗口、屏幕相关信息管理类 * 窗口、屏幕相关信息管理类
*/ */
export class WindowManager { export class WindowManager {
private static instance: WindowManager = null; private static instance: WindowManager|null = null;
private displayInfo: display.Display = null; private displayInfo: display.Display|null = null;
private orientationListener = mediaquery.matchMediaSync('(orientation: landscape)'); private orientationListener = mediaquery.matchMediaSync('(orientation: landscape)');
private portraitFunc = null; private portraitFunc: Function | null = null;
constructor() { constructor() {
this.portraitFunc = this.onPortrait.bind(this); this.portraitFunc = (mediaQueryResult: mediaquery.MediaQueryResult) => { this.onPortrait(mediaQueryResult) };
this.orientationListener.on('change', this.portraitFunc) this.orientationListener.on('change', this.portraitFunc)
this.loadDisplayInfo() this.loadDisplayInfo()
} }
...@@ -88,30 +91,30 @@ export class WindowManager { ...@@ -88,30 +91,30 @@ export class WindowManager {
if (win == null) { if (win == null) {
return return
} }
globalThis.mainWin = win; GlobalContext.mainWin = win;
win.on("windowSizeChange", (data: window.Size) => { win.on("windowSizeChange", (data: window.Size) => {
if (globalThis.mainWindowSize == undefined || globalThis.mainWindowSize == null) { if (GlobalContext.mainWindowSize == undefined || GlobalContext.mainWindowSize == null) {
globalThis.mainWindowSize = data; GlobalContext.mainWindowSize = data;
} else { } else {
if (globalThis.mainWindowSize.width == data.width && globalThis.mainWindowSize.height == data.height) { if (GlobalContext.mainWindowSize.width == data.width && GlobalContext.mainWindowSize.height == data.height) {
return return
} }
globalThis.mainWindowSize = data; GlobalContext.mainWindowSize = data;
} }
let winWidth = this.getMainWindowWidth(); let winWidth = this.getMainWindowWidth();
AppStorage.SetOrCreate<number>('mainWinWidth', winWidth) AppStorage.SetOrCreate<number>('mainWinWidth', winWidth)
let winHeight = this.getMainWindowHeight(); let winHeight = this.getMainWindowHeight();
AppStorage.SetOrCreate<number>('mainWinHeight', winHeight) AppStorage.SetOrCreate<number>('mainWinHeight', winHeight)
globalThis.context.eventHub.emit("windowSizeChange", winWidth, winHeight) GlobalContext.context.eventHub.emit("windowSizeChange", winWidth, winHeight)
}) })
} }
static getInstance(): WindowManager { static getInstance(): WindowManager {
if (this.instance == null) { if (WindowManager.instance == null) {
this.instance = new WindowManager(); WindowManager.instance = new WindowManager();
} }
return this.instance return WindowManager.instance
} }
private onPortrait(mediaQueryResult: mediaquery.MediaQueryResult) { private onPortrait(mediaQueryResult: mediaquery.MediaQueryResult) {
...@@ -127,8 +130,8 @@ export class WindowManager { ...@@ -127,8 +130,8 @@ export class WindowManager {
* @param ori 常量枚举值:window.Orientation * @param ori 常量枚举值:window.Orientation
*/ */
changeOrientation(ori: window.Orientation) { changeOrientation(ori: window.Orientation) {
if (globalThis.mainWin != null) { if (GlobalContext.mainWin != null) {
globalThis.mainWin.setPreferredOrientation(ori) GlobalContext.mainWin.setPreferredOrientation(ori)
} }
} }
...@@ -142,14 +145,14 @@ export class WindowManager { ...@@ -142,14 +145,14 @@ export class WindowManager {
* 获取main窗口宽度,单位vp * 获取main窗口宽度,单位vp
*/ */
getMainWindowWidth(): number { getMainWindowWidth(): number {
return globalThis.mainWindowSize != null ? px2vp(globalThis.mainWindowSize.width) : 0 return GlobalContext.mainWindowSize != null ? px2vp(GlobalContext.mainWindowSize.width) : 0
} }
/** /**
* 获取main窗口高度,单位vp * 获取main窗口高度,单位vp
*/ */
getMainWindowHeight(): number { getMainWindowHeight(): number {
return globalThis.mainWindowSize != null ? px2vp(globalThis.mainWindowSize.height) : 0 return GlobalContext.mainWindowSize != null ? px2vp(GlobalContext.mainWindowSize.height) : 0
} }
/** /**
...@@ -173,8 +176,8 @@ export class WindowManager { ...@@ -173,8 +176,8 @@ export class WindowManager {
if (this.orientationListener) { if (this.orientationListener) {
this.orientationListener.off('change', this.portraitFunc) this.orientationListener.off('change', this.portraitFunc)
} }
if (globalThis.mainWin != null) { if (GlobalContext.mainWin != null) {
globalThis.mainWin.off('windowSizeChange') GlobalContext.mainWin.off('windowSizeChange')
} }
WindowManager.instance = null; WindowManager.instance = null;
} }
...@@ -232,7 +235,7 @@ export struct TaskSwitchMainPage { ...@@ -232,7 +235,7 @@ export struct TaskSwitchMainPage {
@State taskViewOffsetX: number = 0; @State taskViewOffsetX: number = 0;
@State cardOffset: number = this.displayWidth / 4; @State cardOffset: number = this.displayWidth / 4;
lastCardOffset: number = this.cardOffset; lastCardOffset: number = this.cardOffset;
startTime: number startTime: number|undefined=undefined
// 每个卡片初始位置 // 每个卡片初始位置
aboutToAppear() { aboutToAppear() {
...@@ -258,7 +261,8 @@ export struct TaskSwitchMainPage { ...@@ -258,7 +261,8 @@ export struct TaskSwitchMainPage {
// 滑动组件 // 滑动组件
Scroll(this.scroller) { Scroll(this.scroller) {
Row({ space: this.cardSpace }) { Row({ space: this.cardSpace }) {
ForEach(taskDataArr, (item, index) => { ForEach(taskDataArr, (item:TaskData, index:number|undefined) => {
if(index){
Column() Column()
.width(this.cardWidth) .width(this.cardWidth)
.height(this.cardHeight) .height(this.cardHeight)
...@@ -279,7 +283,8 @@ export struct TaskSwitchMainPage { ...@@ -279,7 +283,8 @@ export struct TaskSwitchMainPage {
.translate({ x: this.cardOffset }) .translate({ x: this.cardOffset })
.animation({ curve: curves.springMotion() }) .animation({ curve: curves.springMotion() })
.zIndex((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ? 2 : 1) .zIndex((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ? 2 : 1)
}, item => item.index) }
}, ((item:string):string => item))
} }
.width((this.cardWidth + this.cardSpace) * (taskDataArr.length + 1)) .width((this.cardWidth + this.cardSpace) * (taskDataArr.length + 1))
.height('100%') .height('100%')
...@@ -287,14 +292,21 @@ export struct TaskSwitchMainPage { ...@@ -287,14 +292,21 @@ export struct TaskSwitchMainPage {
.gesture( .gesture(
GestureGroup(GestureMode.Parallel, GestureGroup(GestureMode.Parallel,
PanGesture({ direction: PanDirection.Horizontal, distance: 5 }) PanGesture({ direction: PanDirection.Horizontal, distance: 5 })
.onActionStart((event: GestureEvent) => { .onActionStart((event: GestureEvent|undefined) => {
if(event){
this.startTime = event.timestamp; this.startTime = event.timestamp;
}
}) })
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.cardOffset = this.lastCardOffset + event.offsetX; this.cardOffset = this.lastCardOffset + event.offsetX;
}
}) })
.onActionEnd((event: GestureEvent) => { .onActionEnd((event: GestureEvent|undefined) => {
if(event){
if(this.startTime){
let time = event.timestamp - this.startTime; let time = event.timestamp - this.startTime;
}
let speed = event.offsetX / (time / 1000000000); let speed = event.offsetX / (time / 1000000000);
let moveX = Math.pow(speed, 2) / 7000 * (speed > 0 ? 1 : -1); let moveX = Math.pow(speed, 2) / 7000 * (speed > 0 ? 1 : -1);
...@@ -322,6 +334,7 @@ export struct TaskSwitchMainPage { ...@@ -322,6 +334,7 @@ export struct TaskSwitchMainPage {
// 记录本次滑动偏移量 // 记录本次滑动偏移量
this.lastCardOffset = this.cardOffset; this.lastCardOffset = this.cardOffset;
}
}) })
), GestureMask.IgnoreInternal) ), GestureMask.IgnoreInternal)
.scrollable(ScrollDirection.Horizontal) .scrollable(ScrollDirection.Horizontal)
......
...@@ -54,7 +54,7 @@ class PointClass extends Array<number> { ...@@ -54,7 +54,7 @@ class PointClass extends Array<number> {
} }
add(rhs: PointClass): PointClass { add(rhs: PointClass): PointClass {
let result = new Array<number>() as Point; let result: Point = new Array<number>() as Point;
for (let i = 0; i < 2; i++) { for (let i = 0; i < 2; i++) {
result.push(rhs[i] + this[i]) result.push(rhs[i] + this[i])
} }
...@@ -62,7 +62,7 @@ class PointClass extends Array<number> { ...@@ -62,7 +62,7 @@ class PointClass extends Array<number> {
} }
subtract(rhs: PointClass): PointClass { subtract(rhs: PointClass): PointClass {
let result = new Array<number>() as Point; let result: Point = new Array<number>() as Point;
for (let i = 0; i < 2; i++) { for (let i = 0; i < 2; i++) {
result.push(this[i] - rhs[i]); result.push(this[i] - rhs[i]);
} }
...@@ -70,7 +70,7 @@ class PointClass extends Array<number> { ...@@ -70,7 +70,7 @@ class PointClass extends Array<number> {
} }
multiply(scale: number): PointClass { multiply(scale: number): PointClass {
let result = new Array<number>() as Point; let result: Point = new Array<number>() as Point;
for (let i = 0; i < 2; i++) { for (let i = 0; i < 2; i++) {
result.push(this[i] * scale) result.push(this[i] * scale)
} }
...@@ -84,7 +84,7 @@ class PointVector extends Array<PointClass> implements AnimatableArithmetic<Arra ...@@ -84,7 +84,7 @@ class PointVector extends Array<PointClass> implements AnimatableArithmetic<Arra
constructor(initialValue: Array<Point>) { constructor(initialValue: Array<Point>) {
super(); super();
if (initialValue.length) { if (initialValue.length) {
initialValue.forEach(p => this.push(new PointClass(p))) initialValue.forEach((p:object) => this.push(new PointClass(p)))
} }
} }
...@@ -128,7 +128,7 @@ class PointVector extends Array<PointClass> implements AnimatableArithmetic<Arra ...@@ -128,7 +128,7 @@ class PointVector extends Array<PointClass> implements AnimatableArithmetic<Arra
} }
} }
function randomInt(min, max) { function randomInt(min:number, max:number) {
return Math.floor(Math.random() * (max - min) + min); return Math.floor(Math.random() * (max - min) + min);
} }
......
...@@ -63,7 +63,7 @@ Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRe ...@@ -63,7 +63,7 @@ Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRe
.height('100%') .height('100%')
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
.onReady(() =>{ .onReady(() =>{
var offContext = this.offCanvas.getContext("2d", this.settings) let offContext = this.offCanvas.getContext("2d", this.settings)
//可以在这里绘制内容 //可以在这里绘制内容
offContext.strokeRect(50, 50, 200, 150); offContext.strokeRect(50, 50, 200, 150);
//将离屏绘值渲染的图像在普通画布上显示 //将离屏绘值渲染的图像在普通画布上显示
...@@ -98,13 +98,18 @@ Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRe ...@@ -98,13 +98,18 @@ Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRe
onReady(event: () =&gt; void)是Canvas组件初始化完成时的事件回调,调用该事件后,可获取Canvas组件的确定宽高,进一步使用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象调用相关API进行图形绘制。 onReady(event: () =&gt; void)是Canvas组件初始化完成时的事件回调,调用该事件后,可获取Canvas组件的确定宽高,进一步使用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象调用相关API进行图形绘制。
```ts ```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context) Canvas(this.context)
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
.onReady(() => { .onReady(() => {
this.context.fillStyle = '#0097D4'; let con:Contextset = new Contextset()
this.context.fillRect(50, 50, 100, 100); con.context.fillStyle = '#0097D4';
con.context.fillRect(50, 50, 100, 100);
}) })
``` ```
...@@ -119,15 +124,20 @@ Canvas(this.context) ...@@ -119,15 +124,20 @@ Canvas(this.context)
- 通过CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象直接调用相关API进行绘制。 - 通过CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象直接调用相关API进行绘制。
```ts ```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context) Canvas(this.context)
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
.onReady(() =>{ .onReady(() =>{
this.context.beginPath(); let con:Contextset = new Contextset()
this.context.moveTo(50, 50); con.context.beginPath();
this.context.lineTo(280, 160); con.context.moveTo(50, 50);
this.context.stroke(); con.context.lineTo(280, 160);
con.context.stroke();
}) })
``` ```
...@@ -136,14 +146,19 @@ Canvas(this.context) ...@@ -136,14 +146,19 @@ Canvas(this.context)
- 先单独定义path2d对象构造理想的路径,再通过调用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象的stroke接口或者fill接口进行绘制,具体使用可以参考[Path2D对象](../reference/arkui-ts/ts-components-canvas-path2d.md) - 先单独定义path2d对象构造理想的路径,再通过调用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象的stroke接口或者fill接口进行绘制,具体使用可以参考[Path2D对象](../reference/arkui-ts/ts-components-canvas-path2d.md)
```ts ```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context) Canvas(this.context)
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
.onReady(() =>{ .onReady(() =>{
let con:Contextset = new Contextset()
let region = new Path2D(); let region = new Path2D();
region.arc(100, 75, 50, 0, 6.28); region.arc(100, 75, 50, 0, 6.28);
this.context.stroke(region); con.context.stroke(region);
}) })
``` ```
...@@ -158,23 +173,28 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供 ...@@ -158,23 +173,28 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供
可以通过[arc](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#arc)(绘制弧线路径)、 [ellipse](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#ellipse)(绘制一个椭圆)、[rect](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#rect)(创建矩形路径)等接口绘制基础形状。 可以通过[arc](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#arc)(绘制弧线路径)、 [ellipse](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#ellipse)(绘制一个椭圆)、[rect](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#rect)(创建矩形路径)等接口绘制基础形状。
```ts ```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context) Canvas(this.context)
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
.onReady(() =>{ .onReady(() =>{
let con:Contextset = new Contextset()
//绘制矩形 //绘制矩形
this.context.beginPath(); con.context.beginPath();
this.context.rect(100, 50, 100, 100); con.context.rect(100, 50, 100, 100);
this.context.stroke(); con.context.stroke();
//绘制圆形 //绘制圆形
this.context.beginPath(); con.context.beginPath();
this.context.arc(150, 250, 50, 0, 6.28); con.context.arc(150, 250, 50, 0, 6.28);
this.context.stroke(); con.context.stroke();
//绘制椭圆 //绘制椭圆
this.context.beginPath(); con.context.beginPath();
this.context.ellipse(150, 450, 50, 100, Math.PI * 0.25, Math.PI * 0, Math.PI * 2); con.context.ellipse(150, 450, 50, 100, Math.PI * 0.25, Math.PI * 0, Math.PI * 2);
this.context.stroke(); con.context.stroke();
}) })
``` ```
...@@ -186,17 +206,22 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供 ...@@ -186,17 +206,22 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供
可以通过[fillText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#filltext)(绘制填充类文本)、[strokeText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#stroketext)(绘制描边类文本)等接口进行文本绘制。 可以通过[fillText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#filltext)(绘制填充类文本)、[strokeText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#stroketext)(绘制描边类文本)等接口进行文本绘制。
```ts ```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context) Canvas(this.context)
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
.onReady(() =>{ .onReady(() =>{
let con:Contextset = new Contextset()
//绘制填充类文本 //绘制填充类文本
this.context.font = '50px sans-serif'; con.context.font = '50px sans-serif';
this.context.fillText("Hello World!", 50, 100); con.context.fillText("Hello World!", 50, 100);
//绘制描边类文本 //绘制描边类文本
this.context.font = '55px sans-serif'; con.context.font = '55px sans-serif';
this.context.strokeText("Hello World!", 50, 150); con.context.strokeText("Hello World!", 50, 150);
}) })
``` ```
...@@ -222,7 +247,7 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供 ...@@ -222,7 +247,7 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供
.height('100%') .height('100%')
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
.onReady(() =>{ .onReady(() =>{
var offContext = this.offCanvas.getContext("2d", this.settings) let offContext = this.offCanvas.getContext("2d", this.settings)
// 使用drawImage接口将图片画在(0,0)为起点,宽高130的区域 // 使用drawImage接口将图片画在(0,0)为起点,宽高130的区域
offContext.drawImage(this.img,0,0,130,130); offContext.drawImage(this.img,0,0,130,130);
// 使用getImageData接口,获得canvas组件区域中,(50,50)为起点,宽高130范围内的绘制内容 // 使用getImageData接口,获得canvas组件区域中,(50,50)为起点,宽高130范围内的绘制内容
...@@ -247,20 +272,27 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供 ...@@ -247,20 +272,27 @@ OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供
Canvas中还提供其他类型的方法。渐变([CanvasGradient对象](../reference/arkui-ts/ts-components-canvas-canvasgradient.md))相关的方法:[createLinearGradient](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#createlineargradient)(创建一个线性渐变色)、[createRadialGradient](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#createradialgradient)(创建一个径向渐变色)等。 Canvas中还提供其他类型的方法。渐变([CanvasGradient对象](../reference/arkui-ts/ts-components-canvas-canvasgradient.md))相关的方法:[createLinearGradient](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#createlineargradient)(创建一个线性渐变色)、[createRadialGradient](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#createradialgradient)(创建一个径向渐变色)等。
```ts ```ts
class Contextset{
settings: RenderingContextSettings = new RenderingContextSettings(true)
context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
}
Canvas(this.context) Canvas(this.context)
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
.onReady(() =>{ .onReady(() =>{
let con:Contextset = new Contextset()
//创建一个径向渐变色的CanvasGradient对象 //创建一个径向渐变色的CanvasGradient对象
let grad = this.context.createRadialGradient(200,200,50, 200,200,200) let grad:CanvasRenderingContext2D|undefined = con.context.createRadialGradient(200,200,50, 200,200,200)
//为CanvasGradient对象设置渐变断点值,包括偏移和颜色 //为CanvasGradient对象设置渐变断点值,包括偏移和颜色
if(grad){
grad.addColorStop(0.0, '#E87361'); grad.addColorStop(0.0, '#E87361');
grad.addColorStop(0.5, '#FFFFF0'); grad.addColorStop(0.5, '#FFFFF0');
grad.addColorStop(1.0, '#BDDB69'); grad.addColorStop(1.0, '#BDDB69');
con.context.fillStyle = grad;
}
//用CanvasGradient对象填充矩形 //用CanvasGradient对象填充矩形
this.context.fillStyle = grad; con.context.fillRect(0, 0, 400, 400);
this.context.fillRect(0, 0, 400, 400);
}) })
``` ```
......
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
```ts ```ts
// 出现时会是所有转场效果的出现效果叠加,消失时会是所有消失转场效果的叠加 // 出现时会是所有转场效果的出现效果叠加,消失时会是所有消失转场效果的叠加
// 用于说明各个effect跟随的动画参数 // 用于说明各个effect跟随的动画参数
private effect: TransitionEffect = private effect: object =
TransitionEffect.OPACITY // 创建了透明度转场效果,这里没有调用animation接口,会跟随animateTo的动画参数 TransitionEffect.OPACITY // 创建了透明度转场效果,这里没有调用animation接口,会跟随animateTo的动画参数
// 通过combine方法,添加缩放转场效果,并指定了springMotion(0.6, 1.2)曲线 // 通过combine方法,添加缩放转场效果,并指定了springMotion(0.6, 1.2)曲线
.combine(TransitionEffect.scale({ x: 0, y: 0 }).animation({curve: curves.springMotion(0.6, 1.2) })) .combine(TransitionEffect.scale({ x: 0, y: 0 }).animation({curve: curves.springMotion(0.6, 1.2) }))
......
...@@ -52,6 +52,20 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei ...@@ -52,6 +52,20 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
- 通过形状视口对图形进行放大与缩小。 - 通过形状视口对图形进行放大与缩小。
```ts ```ts
class tmp{
x:number = 0
y:number = 0
width:number = 75
height:number = 75
}
let viep:tmp = new tmp()
class tmp1{
x:number = 0
y:number = 0
width:number = 300
height:number = 300
}
let viep1:tmp1 = new tmp1()
// 画一个宽高都为150的圆 // 画一个宽高都为150的圆
Text('原始尺寸Circle组件') Text('原始尺寸Circle组件')
Circle({width: 75, height: 75}).fill('#E87361') Circle({width: 75, height: 75}).fill('#E87361')
...@@ -65,7 +79,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei ...@@ -65,7 +79,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
Rect().width('100%').height('100%').fill('#0097D4') Rect().width('100%').height('100%').fill('#0097D4')
Circle({width: 75, height: 75}).fill('#E87361') Circle({width: 75, height: 75}).fill('#E87361')
} }
.viewPort({x: 0, y: 0, width: 75, height: 75}) .viewPort(viep)
.width(150) .width(150)
.height(150) .height(150)
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
...@@ -78,7 +92,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei ...@@ -78,7 +92,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
Rect().width('100%').height('100%').fill('#BDDB69') Rect().width('100%').height('100%').fill('#BDDB69')
Circle({width: 75, height: 75}).fill('#E87361') Circle({width: 75, height: 75}).fill('#E87361')
} }
.viewPort({x: 0, y: 0, width: 300, height: 300}) .viewPort(viep1)
.width(150) .width(150)
.height(150) .height(150)
.backgroundColor('#F5DC62') .backgroundColor('#F5DC62')
...@@ -91,11 +105,25 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei ...@@ -91,11 +105,25 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
- 创建一个宽高都为300的shape组件,背景色为黄色,一个宽高都为300的viewport。用一个蓝色的矩形来填充viewport,在viewport中绘制一个半径为75的圆。 - 创建一个宽高都为300的shape组件,背景色为黄色,一个宽高都为300的viewport。用一个蓝色的矩形来填充viewport,在viewport中绘制一个半径为75的圆。
```ts ```ts
class tmp{
x:number = 0
y:number = 0
width:number = 300
height:number = 300
}
let viep:tmp = new tmp()
class tmp1{
x:number = -150
y:number = -150
width:number = 300
height:number = 300
}
let viep1:tmp1 = new tmp1()
Shape() { Shape() {
Rect().width("100%").height("100%").fill("#0097D4") Rect().width("100%").height("100%").fill("#0097D4")
Circle({ width: 150, height: 150 }).fill("#E87361") Circle({ width: 150, height: 150 }).fill("#E87361")
} }
.viewPort({ x: 0, y: 0, width: 300, height: 300 }) .viewPort(viep)
.width(300) .width(300)
.height(300) .height(300)
.backgroundColor("#F5DC62") .backgroundColor("#F5DC62")
...@@ -110,7 +138,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei ...@@ -110,7 +138,7 @@ viewPort{ x?: number | string, y?: number | string, width?: number | string, hei
Rect().width("100%").height("100%").fill("#0097D4") Rect().width("100%").height("100%").fill("#0097D4")
Circle({ width: 150, height: 150 }).fill("#E87361") Circle({ width: 150, height: 150 }).fill("#E87361")
} }
.viewPort({ x: -150, y: -150, width: 300, height: 300 }) .viewPort(viep1)
.width(300) .width(300)
.height(300) .height(300)
.backgroundColor("#F5DC62") .backgroundColor("#F5DC62")
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
```ts ```ts
GestureGroup(mode:GestureMode, ...gesture:GestureType[]) GestureGroup(mode:GestureMode, gesture:GestureType[])
``` ```
...@@ -53,10 +53,12 @@ struct Index { ...@@ -53,10 +53,12 @@ struct Index {
// 该组合手势第一个触发的手势为长按手势,且长按手势可多次响应 // 该组合手势第一个触发的手势为长按手势,且长按手势可多次响应
LongPressGesture({ repeat: true }) LongPressGesture({ repeat: true })
// 当长按手势识别成功,增加Text组件上显示的count次数 // 当长按手势识别成功,增加Text组件上显示的count次数
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent|undefined) => {
if(event){
if (event.repeat) { if (event.repeat) {
this.count++; this.count++;
} }
}
console.info('LongPress onAction'); console.info('LongPress onAction');
}) })
.onActionEnd(() => { .onActionEnd(() => {
...@@ -69,9 +71,11 @@ struct Index { ...@@ -69,9 +71,11 @@ struct Index {
console.info('pan start'); console.info('pan start');
}) })
// 当该手势被触发时,根据回调获得拖动的距离,修改该组件的位移距离从而实现组件的移动 // 当该手势被触发时,根据回调获得拖动的距离,修改该组件的位移距离从而实现组件的移动
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.offsetX = this.positionX + event.offsetX; this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY; this.offsetY = this.positionY + event.offsetY;
}
console.info('pan update'); console.info('pan update');
}) })
.onActionEnd(() => { .onActionEnd(() => {
......
...@@ -30,8 +30,10 @@ TapGesture(value?:{count?:number; fingers?:number}) ...@@ -30,8 +30,10 @@ TapGesture(value?:{count?:number; fingers?:number})
.gesture( .gesture(
// 绑定count为2的TapGesture // 绑定count为2的TapGesture
TapGesture({ count: 2 }) TapGesture({ count: 2 })
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent|undefined) => {
if(event){
this.value = JSON.stringify(event.fingerList[0]); this.value = JSON.stringify(event.fingerList[0]);
}
})) }))
Text(this.value) Text(this.value)
} }
...@@ -82,10 +84,12 @@ struct Index { ...@@ -82,10 +84,12 @@ struct Index {
.gesture( .gesture(
// 绑定可以重复触发的LongPressGesture // 绑定可以重复触发的LongPressGesture
LongPressGesture({ repeat: true }) LongPressGesture({ repeat: true })
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent|undefined) => {
if(event){
if (event.repeat) { if (event.repeat) {
this.count++; this.count++;
} }
}
}) })
.onActionEnd(() => { .onActionEnd(() => {
this.count = 0; this.count = 0;
...@@ -109,7 +113,13 @@ struct Index { ...@@ -109,7 +113,13 @@ struct Index {
```ts ```ts
PanGestureOptions(value?:{ fingers?:number; direction?:PanDirection; distance?:number}) class pgotmp{
fingers?:number = 0
direction?:PanDirection|null = null
distance?:number = 0
}
let pgo:pgotmp = new pgotmp()
new PanGestureOptions(value?:pgo)
``` ```
...@@ -150,13 +160,15 @@ struct Index { ...@@ -150,13 +160,15 @@ struct Index {
.gesture( .gesture(
// 绑定拖动手势 // 绑定拖动手势
PanGesture() PanGesture()
.onActionStart((event: GestureEvent) => { .onActionStart((event: GestureEvent|undefined) => {
console.info('Pan start'); console.info('Pan start');
}) })
// 当触发拖动手势时,根据回调函数修改组件的布局位置信息 // 当触发拖动手势时,根据回调函数修改组件的布局位置信息
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.offsetX = this.positionX + event.offsetX; this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY; this.offsetY = this.positionY + event.offsetY;
}
}) })
.onActionEnd(() => { .onActionEnd(() => {
this.positionX = this.offsetX; this.positionX = this.offsetX;
...@@ -226,14 +238,16 @@ struct Index { ...@@ -226,14 +238,16 @@ struct Index {
.gesture( .gesture(
// 在组件上绑定三指触发的捏合手势 // 在组件上绑定三指触发的捏合手势
PinchGesture({ fingers: 3 }) PinchGesture({ fingers: 3 })
.onActionStart((event: GestureEvent) => { .onActionStart((event: GestureEvent|undefined) => {
console.info('Pinch start'); console.info('Pinch start');
}) })
// 当捏合手势触发时,可以通过回调函数获取缩放比例,从而修改组件的缩放比例 // 当捏合手势触发时,可以通过回调函数获取缩放比例,从而修改组件的缩放比例
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.scaleValue = this.pinchValue * event.scale; this.scaleValue = this.pinchValue * event.scale;
this.pinchX = event.pinchCenterX; this.pinchX = event.pinchCenterX;
this.pinchY = event.pinchCenterY; this.pinchY = event.pinchCenterY;
}
}) })
.onActionEnd(() => { .onActionEnd(() => {
this.pinchValue = this.scaleValue; this.pinchValue = this.scaleValue;
...@@ -284,12 +298,14 @@ struct Index { ...@@ -284,12 +298,14 @@ struct Index {
.rotate({ angle: this.angle }) .rotate({ angle: this.angle })
.gesture( .gesture(
RotationGesture() RotationGesture()
.onActionStart((event: GestureEvent) => { .onActionStart((event: GestureEvent|undefined) => {
console.info('RotationGesture is onActionStart'); console.info('RotationGesture is onActionStart');
}) })
// 当旋转手势生效时,通过旋转手势的回调函数获取旋转角度,从而修改组件的旋转角度 // 当旋转手势生效时,通过旋转手势的回调函数获取旋转角度,从而修改组件的旋转角度
.onActionUpdate((event: GestureEvent) => { .onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.angle = this.rotateValue + event.angle; this.angle = this.rotateValue + event.angle;
}
console.info('RotationGesture is onActionEnd'); console.info('RotationGesture is onActionEnd');
}) })
// 当旋转结束抬手时,固定组件在旋转结束时的角度 // 当旋转结束抬手时,固定组件在旋转结束时的角度
...@@ -358,9 +374,11 @@ struct Index { ...@@ -358,9 +374,11 @@ struct Index {
// 绑定滑动手势且限制仅在竖直方向滑动时触发 // 绑定滑动手势且限制仅在竖直方向滑动时触发
SwipeGesture({ direction: SwipeDirection.Vertical }) SwipeGesture({ direction: SwipeDirection.Vertical })
// 当滑动手势触发时,获取滑动的速度和角度,实现对组件的布局参数的修改 // 当滑动手势触发时,获取滑动的速度和角度,实现对组件的布局参数的修改
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent|undefined) => {
if(event){
this.speed = event.speed; this.speed = event.speed;
this.rotateAngle = event.angle; this.rotateAngle = event.angle;
}
}) })
) )
} }
......
...@@ -86,18 +86,20 @@ Image支持加载存档图、多媒体像素图两种类型。 ...@@ -86,18 +86,20 @@ Image支持加载存档图、多媒体像素图两种类型。
getAllImg() { getAllImg() {
let result = new Array<string>(); let result = new Array<string>();
try { try {
let PhotoSelectOptions = new picker.PhotoSelectOptions(); let PhotoSelectOptions:picker.PhotoSelectOptions = new picker.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 5; PhotoSelectOptions.maxSelectNumber = 5;
let photoPicker = new picker.PhotoViewPicker(); let photoPicker:picker.PhotoViewPicker = new picker.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => { photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult:picker.PhotoSelectResult) => {
this.imgDatas = PhotoSelectResult.photoUris; this.imgDatas = PhotoSelectResult.photoUris;
console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
}).catch((err) => { }).catch((err:Error) => {
console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`); console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`);
}); });
} catch (err) { } catch (err) {
console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`); } let message:BusinessError = (err as BusinessError).message;
let code:BusinessError = (err as BusinessError).code;
console.error(`PhotoViewPicker failed with. Code: ${code}, message: ${message}`); }
} }
// aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中 // aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中
...@@ -108,12 +110,12 @@ Image支持加载存档图、多媒体像素图两种类型。 ...@@ -108,12 +110,12 @@ Image支持加载存档图、多媒体像素图两种类型。
build() { build() {
Column() { Column() {
Grid() { Grid() {
ForEach(this.imgDatas, item => { ForEach(this.imgDatas, (item:string) => {
GridItem() { GridItem() {
Image(item) Image(item)
.width(200) .width(200)
} }
}, item => JSON.stringify(item)) }, ((item:string):string => JSON.stringify(item)))
} }
}.width('100%').height('100%') }.width('100%').height('100%')
} }
...@@ -156,7 +158,7 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指 ...@@ -156,7 +158,7 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指
2. 填写网络图片地址。 2. 填写网络图片地址。
```ts ```ts
http.createHttp().request("https://www.example.com/xxx.png", http.createHttp().request("https://www.example.com/xxx.png",
(error, data) => { (error:Error) => {
if (error){ if (error){
console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`); console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
} else { } else {
...@@ -166,27 +168,47 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指 ...@@ -166,27 +168,47 @@ PixelMap是图片解码后的像素图,具体用法请参考[图片开发指
``` ```
3. 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。 3. 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。
```ts ```ts
let code = data.responseCode; let code:object = data.responseCode;
if (ResponseCode.ResponseCode.OK === code) { if (ResponseCode.ResponseCode.OK === code) {
let res: any = data.result let imageSource:image = image.createImageSource(data.result);
let imageSource = image.createImageSource(res); class tmp{
let options = { height:number = 100
alphaType: 0, // 透明度 width:number = 100
editable: false, // 是否可编辑 }
pixelFormat: 3, // 像素格式 let si:tmp = new tmp()
scaleMode: 1, // 缩略值 let options:Record<string,number|boolean|tmp> = {
size: { height: 100, width: 100 } 'alphaType': 0, // 透明度
'editable': false, // 是否可编辑
'pixelFormat': 3, // 像素格式
'scaleMode': 1, // 缩略值
'size': { height: 100, width: 100 }
} // 创建图片大小 } // 创建图片大小
imageSource.createPixelMap(options).then((pixelMap) => { class imagetmp{
this.image = pixelMap image:image
set(val:PixelMap){
this.image = val
}
}
imageSource.createPixelMap(options).then((pixelMap:PixelMap) => {
let im = new imagetmp()
im.set(pixelMap)
}) })
} }
``` ```
4. 显示图片。 4. 显示图片。
```ts ```ts
class htp{
httpRequest:Function|undefined = undefined
set(){
if(this.httpRequest){
this.httpRequest()
}
}
}
Button("获取网络图片") Button("获取网络图片")
.onClick(() => { .onClick(() => {
this.httpRequest() let sethtp = new htp()
sethtp.set()
}) })
Image(this.image).height(100).width(100) Image(this.image).height(100).width(100)
``` ```
...@@ -498,6 +520,14 @@ Image($r('app.media.icon')) ...@@ -498,6 +520,14 @@ Image($r('app.media.icon'))
```ts ```ts
class tmp{
width: number = 0
height: number = 0
componentWidth: number = 0
componentHeight: number = 0
}
let msg:tmp = new tmp()
@Entry @Entry
@Component @Component
struct MyComponent { struct MyComponent {
...@@ -513,16 +543,13 @@ struct MyComponent { ...@@ -513,16 +543,13 @@ struct MyComponent {
.width(200) .width(200)
.height(150) .height(150)
.margin(15) .margin(15)
.onComplete((msg: { .onComplete(msg => {
width: number, if(msg){
height: number,
componentWidth: number,
componentHeight: number
}) => {
this.widthValue = msg.width this.widthValue = msg.width
this.heightValue = msg.height this.heightValue = msg.height
this.componentWidth = msg.componentWidth this.componentWidth = msg.componentWidth
this.componentHeight = msg.componentHeight this.componentHeight = msg.componentHeight
}
}) })
// 图片获取失败,打印结果 // 图片获取失败,打印结果
.onError(() => { .onError(() => {
......
...@@ -185,15 +185,14 @@ struct OfficeService { ...@@ -185,15 +185,14 @@ struct OfficeService {
build() { build() {
Column() { Column() {
Grid() { Grid() {
ForEach(this.services, service => { ForEach(this.services, (service:string) => {
GridItem() { GridItem() {
Text(service) Text(service)
...
} }
}, service => service) }, ((service:string):string => service))
} }
.rowsTemplate('1fr 1fr') .rowsTemplate(('1fr 1fr') as string)
.columnsTemplate('1fr 1fr') .columnsTemplate(('1fr 1fr') as string)
... ...
} }
... ...
...@@ -238,24 +237,20 @@ Grid() { ...@@ -238,24 +237,20 @@ Grid() {
```ts ```ts
@Component @Component
struct Shopping { struct Shopping {
@State services: Array<string> = ['直播', '进口', ...] @State services: Array<string> = ['直播', '进口']
...
build() { build() {
Column({ space: 5 }) { Column({ space: 5 }) {
Grid() { Grid() {
ForEach(this.services, (service: string, index) => { ForEach(this.services, (service: string, index) => {
GridItem() { GridItem() {
...
} }
.width('25%') .width('25%')
}, service => service) }, ((service:string):string => service))
} }
.rowsTemplate('1fr 1fr') // 只设置rowsTemplate属性,当内容超出Grid区域时,可水平滚动。 .rowsTemplate('1fr 1fr') // 只设置rowsTemplate属性,当内容超出Grid区域时,可水平滚动。
.rowsGap(15) .rowsGap(15)
...
} }
...
} }
} }
``` ```
...@@ -273,13 +268,19 @@ Grid组件初始化时,可以绑定一个[Scroller](../reference/arkui-ts/ts-c ...@@ -273,13 +268,19 @@ Grid组件初始化时,可以绑定一个[Scroller](../reference/arkui-ts/ts-c
```ts ```ts
private scroller: Scroller = new Scroller() export let scroller: Scroller = new Scroller()
``` ```
在日历页面中,用户在点击“下一页”按钮时,应用响应点击事件,通过指定scrollPage方法的参数next为true,滚动到下一页。 在日历页面中,用户在点击“下一页”按钮时,应用响应点击事件,通过指定scrollPage方法的参数next为true,滚动到下一页。
```ts ```ts
class Tmp{
scroller: Scroller = new Scroller()
set(boo:boolean){
this.scroller.scrollPage({next:boo})
}
}
Column({ space: 5 }) { Column({ space: 5 }) {
Grid(this.scroller) { Grid(this.scroller) {
... ...
...@@ -290,16 +291,14 @@ Column({ space: 5 }) { ...@@ -290,16 +291,14 @@ Column({ space: 5 }) {
Row({space: 20}) { Row({space: 20}) {
Button('上一页') Button('上一页')
.onClick(() => { .onClick(() => {
this.scroller.scrollPage({ let ClickN = new Tmp()
next: false ClickN.set(false)
})
}) })
Button('下一页') Button('下一页')
.onClick(() => { .onClick(() => {
this.scroller.scrollPage({ let ClickN = new Tmp()
next: true ClickN.set(true)
})
}) })
} }
} }
...@@ -319,9 +318,8 @@ Column({ space: 5 }) { ...@@ -319,9 +318,8 @@ Column({ space: 5 }) {
```ts ```ts
Grid() { Grid() {
LazyForEach(this.dataSource, item => { LazyForEach(this.dataSource, () => {
GridItem() { GridItem() {
...
} }
}) })
} }
......
...@@ -99,20 +99,30 @@ List组件的lanes属性通常用于在不同尺寸的设备自适应构建不 ...@@ -99,20 +99,30 @@ List组件的lanes属性通常用于在不同尺寸的设备自适应构建不
```ts ```ts
class Tmp{
minLength:number = 200
maxLength:number = 300
}
let Mn:Tmp = new Tmp()
List() { List() {
... ...
} }
.lanes(2) .lanes(Mn)
``` ```
当其取值为LengthConstrain类型时,表示会根据LengthConstrain与List组件的尺寸自适应决定行或列数。 当其取值为LengthConstrain类型时,表示会根据LengthConstrain与List组件的尺寸自适应决定行或列数。
```ts ```ts
class Tmp{
minLength:number = 200
maxLength:number = 300
}
let mn:Tmp = new Tmp()
List() { List() {
... ...
} }
.lanes({ minLength: 200, maxLength: 300 }) .lanes(mn)
``` ```
例如,假设在垂直列表中设置了lanes的值为{ minLength: 200, maxLength: 300 }。此时, 例如,假设在垂直列表中设置了lanes的值为{ minLength: 200, maxLength: 300 }。此时,
...@@ -229,10 +239,9 @@ class Contact { ...@@ -229,10 +239,9 @@ class Contact {
@Entry @Entry
@Component @Component
struct SimpleContacts { struct SimpleContacts {
private contacts = [ private contacts:Array<object> = [
new Contact('小明', $r("app.media.iconA")), new Contact('小明', $r("app.media.iconA")),
new Contact('小红', $r("app.media.iconB")), new Contact('小红', $r("app.media.iconB")),
...
] ]
build() { build() {
...@@ -249,7 +258,7 @@ struct SimpleContacts { ...@@ -249,7 +258,7 @@ struct SimpleContacts {
.width('100%') .width('100%')
.justifyContent(FlexAlign.Start) .justifyContent(FlexAlign.Start)
} }
}, item => item.key) }, ((item:Contact):string => item.key))
} }
.width('100%') .width('100%')
} }
...@@ -288,15 +297,16 @@ startMargin和endMargin属性分别用于设置分隔线距离列表侧边起始 ...@@ -288,15 +297,16 @@ startMargin和endMargin属性分别用于设置分隔线距离列表侧边起始
```ts ```ts
let opt = {
'strokeWidth': 1,
'startMargin': 60,
'endMargin': 10,
'color': '#ffe9f0f0'
} as Record<string,number|string>
List() { List() {
... ...
} }
.divider({ .divider(opt)
strokeWidth: 1,
startMargin: 60,
endMargin: 10,
color: '#ffe9f0f0'
})
``` ```
此示例表示从距离列表侧边起始端60vp开始到距离结束端10vp的位置,画一条粗细为1vp的分割线,可以实现图9设置列表分隔线的样式。 此示例表示从距离列表侧边起始端60vp开始到距离结束端10vp的位置,画一条粗细为1vp的分割线,可以实现图9设置列表分隔线的样式。
...@@ -378,7 +388,11 @@ struct ContactsList { ...@@ -378,7 +388,11 @@ struct ContactsList {
```ts ```ts
contactsGroups: object[] = [ class cgtmp{
title:string = ''
contacts:Array<object>|null = null
}
export let contactsGroups: object[] = [
{ {
title: 'A', title: 'A',
contacts: [ contacts: [
...@@ -386,15 +400,14 @@ contactsGroups: object[] = [ ...@@ -386,15 +400,14 @@ contactsGroups: object[] = [
new Contact('安安', $r('app.media.iconB')), new Contact('安安', $r('app.media.iconB')),
new Contact('Angela', $r('app.media.iconC')), new Contact('Angela', $r('app.media.iconC')),
], ],
}, } as cgtmp,
{ {
title: 'B', title: 'B',
contacts: [ contacts: [
new Contact('白叶', $r('app.media.iconD')), new Contact('白叶', $r('app.media.iconD')),
new Contact('伯明', $r('app.media.iconE')), new Contact('伯明', $r('app.media.iconE')),
], ],
}, } as cgtmp,
...
] ]
``` ```
...@@ -402,18 +415,30 @@ contactsGroups: object[] = [ ...@@ -402,18 +415,30 @@ contactsGroups: object[] = [
```ts ```ts
class cgtmpf{
title:string = ''
contacts:Array<object>|null = null
key:string = ''
}
class heF{
itemHead:Function = (text: string) => {}
foo(val:string){
this.itemHead(val)
}
}
let fff:heF = this.heF()
List() { List() {
// 循环渲染ListItemGroup,contactsGroups为多个分组联系人contacts和标题title的数据集合 // 循环渲染ListItemGroup,contactsGroups为多个分组联系人contacts和标题title的数据集合
ForEach(this.contactsGroups, item => { ForEach(contactsGroups, (item: cgtmpf) => {
ListItemGroup({ header: this.itemHead(item.title) }) { ListItemGroup({ header: fff(item.title) }) {
// 循环渲染ListItem // 循环渲染ListItem
ForEach(item.contacts, (contact) => { if (item.contacts) {
ForEach(item.contacts, () => {
ListItem() { ListItem() {
...
} }
}, item => item.key) }, ((item: cgtmpf): string => item.key))
}
} }
...
}) })
} }
``` ```
...@@ -452,16 +477,16 @@ struct ContactsList { ...@@ -452,16 +477,16 @@ struct ContactsList {
build() { build() {
List() { List() {
// 循环渲染ListItemGroup,contactsGroups为多个分组联系人contacts和标题title的数据集合 // 循环渲染ListItemGroup,contactsGroups为多个分组联系人contacts和标题title的数据集合
ForEach(this.contactsGroups, item => { ForEach(contactsGroups, (item:cgtmpf) => {
ListItemGroup({ header: this.itemHead(item.title) }) { ListItemGroup({ header: this.itemHead(item.title) }) {
// 循环渲染ListItem // 循环渲染ListItem
ForEach(item.contacts, (contact) => { if(item.contacts){
ForEach(item.contacts, () => {
ListItem() { ListItem() {
...
} }
}, item => item.key) }, ((item:cgtmpf):string => item.key))
}
} }
...
}) })
} }
.sticky(StickyStyle.Header) // 设置吸顶,实现粘性标题效果 .sticky(StickyStyle.Header) // 设置吸顶,实现粘性标题效果
...@@ -484,14 +509,15 @@ List组件初始化时,可以通过scroller参数绑定一个[Scroller](../ref ...@@ -484,14 +509,15 @@ List组件初始化时,可以通过scroller参数绑定一个[Scroller](../ref
```ts ```ts
private listScroller: Scroller = new Scroller(); export let listScroller: Scroller = new Scroller();
``` ```
然后,通过将listScroller用于初始化List组件的scroller参数,完成listScroller与列表的绑定。在需要跳转的位置指定scrollToIndex的参数为0,表示返回列表顶部。 然后,通过将listScroller用于初始化List组件的scroller参数,完成listScroller与列表的绑定。在需要跳转的位置指定scrollToIndex的参数为0,表示返回列表顶部。
```ts ```ts
Stack({ alignContent: Alignment.BottomEnd }) { let sttmo:Record<string,Alignment> = { 'alignContent': Alignment.BottomEnd }
Stack(sttmo) {
// 将listScroller用于初始化List组件的scroller参数,完成listScroller与列表的绑定。 // 将listScroller用于初始化List组件的scroller参数,完成listScroller与列表的绑定。
List({ space: 20, scroller: this.listScroller }) { List({ space: 20, scroller: this.listScroller }) {
... ...
...@@ -503,7 +529,7 @@ Stack({ alignContent: Alignment.BottomEnd }) { ...@@ -503,7 +529,7 @@ Stack({ alignContent: Alignment.BottomEnd }) {
} }
.onClick(() => { .onClick(() => {
// 点击按钮时,指定跳转位置,返回列表顶部 // 点击按钮时,指定跳转位置,返回列表顶部
this.listScroller.scrollToIndex(0) listScroller.scrollToIndex(0)
}) })
... ...
} }
...@@ -544,7 +570,6 @@ struct ContactsList { ...@@ -544,7 +570,6 @@ struct ContactsList {
} }
.onScrollIndex((firstIndex: number) => { .onScrollIndex((firstIndex: number) => {
// 根据列表滚动到的索引值,重新计算对应联系人索引栏的位置this.selectedIndex // 根据列表滚动到的索引值,重新计算对应联系人索引栏的位置this.selectedIndex
...
}) })
... ...
...@@ -576,12 +601,22 @@ ListItem的swipeAction属性可用于实现列表项的左右滑动功能。swip ...@@ -576,12 +601,22 @@ ListItem的swipeAction属性可用于实现列表项的左右滑动功能。swip
```ts ```ts
class swtmp{
temp:Record<string,object> = {}
itemEnd:Function|undefined = undefined
get(index:number){
if(this.itemEnd){
this.temp = {'end':this.itemEnd(this, index)}
}
return this.temp
}
}
let swipertmp:swtmp = new swtmp()
@Entry @Entry
@Component @Component
struct MessageList { struct MessageList {
@State messages: object[] = [ @State messages: object[] = [
// 初始化消息列表数据 // 初始化消息列表数据
...
]; ];
@Builder itemEnd(index: number) { @Builder itemEnd(index: number) {
...@@ -600,12 +635,13 @@ struct MessageList { ...@@ -600,12 +635,13 @@ struct MessageList {
build() { build() {
... ...
List() { List() {
ForEach(this.messages, (item, index) => { ForEach(this.messages, (item:MessageList, index:number|undefined) => {
if(index){
ListItem() { ListItem() {
...
} }
.swipeAction({ end: this.itemEnd.bind(this, index) }) // 设置侧滑属性 .swipeAction(swipertmp.get(index)) // 设置侧滑属性.
}, item => item.id.toString()) }
}, ((item:MessageList):string => item.id.toString()))
} }
... ...
} }
...@@ -691,18 +727,27 @@ Badge({ ...@@ -691,18 +727,27 @@ Badge({
```ts ```ts
@State toDoData: ToDo[] = []; @State toDoData: ToDo[] = [];
private availableThings: string[] = ['读书', '运动', '旅游', '听音乐', '看电影', '唱歌']; export let availableThings: string[] = ['读书', '运动', '旅游', '听音乐', '看电影', '唱歌'];
``` ```
最后,构建列表布局和列表项: 最后,构建列表布局和列表项:
```ts ```ts
export class ToDo {
key: string = util.generateRandomUUID(true);
name: string;
toDoData:ToDo[] = [];
constructor(name: string) {
this.name = name;
}
}
let todo:ToDo = new ToDo()
List({ space: 10 }) { List({ space: 10 }) {
ForEach(this.toDoData, (toDoItem) => { ForEach(todo.toDoData, (toDoItem:ToDo) => {
ListItem() { ListItem() {
...
} }
}, toDoItem => toDoItem.key) }, ((toDoItem:ToDo):string => toDoItem.key))
} }
``` ```
...@@ -715,9 +760,9 @@ Badge({ ...@@ -715,9 +760,9 @@ Badge({
Text('+') Text('+')
.onClick(() => { .onClick(() => {
TextPickerDialog.show({ TextPickerDialog.show({
range: this.availableThings, range: availableThings,
onAccept: (value: TextPickerResult) => { onAccept: (value: TextPickerResult) => {
this.toDoData.push(new ToDo(this.availableThings[value.index])); // 新增列表项数据toDoData todo.toDoData.push(new ToDo(availableThings[value.index])); // 新增列表项数据toDoData
}, },
}) })
}) })
...@@ -738,6 +783,13 @@ Badge({ ...@@ -738,6 +783,13 @@ Badge({
以待办列表为例,通过监听列表项的长按事件,当用户长按列表项时,进入编辑模式。 以待办列表为例,通过监听列表项的长按事件,当用户长按列表项时,进入编辑模式。
```ts ```ts
class todoTmp{
isEditMode:boolean = false
selectedItems:Array<object> = []
toDoItem:ToDo[] = [];
toDoData:ToDo[] = [];
}
let todolist:todoTmp = new todoTmp()
// ToDoListItem.ets // ToDoListItem.ets
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
...@@ -747,9 +799,9 @@ Badge({ ...@@ -747,9 +799,9 @@ Badge({
GestureGroup(GestureMode.Exclusive, GestureGroup(GestureMode.Exclusive,
LongPressGesture() LongPressGesture()
.onAction(() => { .onAction(() => {
if (!this.isEditMode) { if (!todolist.isEditMode) {
this.isEditMode = true; //进入编辑模式 todolist.isEditMode = true; //进入编辑模式
this.selectedItems.push(this.toDoItem); // 记录长按时选中的列表项 todolist.selectedItems.push(todolist.toDoItem); // 记录长按时选中的列表项
} }
}) })
) )
...@@ -760,17 +812,34 @@ Badge({ ...@@ -760,17 +812,34 @@ Badge({
在待办列表中,通过勾选框的勾选或取消勾选,响应用户勾选列表项变化,记录所有选择的列表项。 在待办列表中,通过勾选框的勾选或取消勾选,响应用户勾选列表项变化,记录所有选择的列表项。
```ts ```ts
import util from '@ohos.util';
export class ToDo {
key: string = util.generateRandomUUID(true);
name: string;
toDoData:ToDo[] = [];
constructor(name: string) {
this.name = name;
}
}
class todoTmp{
isEditMode:boolean = false
selectedItems:Array<object> = []
toDoItem:ToDo[] = [];
toDoData:ToDo[] = [];
}
let todolist:todoTmp = new todoTmp()
// ToDoListItem.ets // ToDoListItem.ets
if (this.isEditMode) { if (todolist.isEditMode) {
Checkbox() Checkbox()
.onChange((isSelected) => { .onChange((isSelected) => {
if (isSelected) { if (isSelected) {
this.selectedItems.push(this.toDoItem) // 勾选时,记录选中的列表项 todolist.selectedItems.push(todolist.toDoItem) // 勾选时,记录选中的列表项
} else { } else {
let index = this.selectedItems.indexOf(this.toDoItem) let index = todolist.selectedItems.indexOf(todolist.toDoItem)
if (index !== -1) { if (index !== -1) {
this.selectedItems.splice(index, 1) // 取消勾选时,则将此项从selectedItems中删除 todolist.selectedItems.splice(index, 1) // 取消勾选时,则将此项从selectedItems中删除
} }
} }
}) })
...@@ -781,17 +850,34 @@ Badge({ ...@@ -781,17 +850,34 @@ Badge({
3. 需要响应用户点击删除按钮事件,删除列表中对应的选项。 3. 需要响应用户点击删除按钮事件,删除列表中对应的选项。
```ts ```ts
import util from '@ohos.util';
export class ToDo {
key: string = util.generateRandomUUID(true);
name: string;
toDoData:ToDo[] = [];
constructor(name: string) {
this.name = name;
}
}
class todoTmp{
isEditMode:boolean = false
selectedItems:Array<object> = []
toDoItem:ToDo[] = [];
toDoData:ToDo[] = [];
}
let todolist:todoTmp = new todoTmp()
// ToDoList.ets // ToDoList.ets
Button('删除') Button('删除')
.onClick(() => { .onClick(() => {
// 删除选中的列表项对应的toDoData数据 // 删除选中的列表项对应的toDoData数据
let leftData = this.toDoData.filter((item) => { let leftData = todolist.toDoData.filter((item) => {
return this.selectedItems.find((selectedItem) => selectedItem !== item); return todolist.selectedItems.find((selectedItem) => selectedItem !== item);
}) })
this.toDoData = leftData; todolist.toDoData = leftData;
this.isEditMode = false; todolist.isEditMode = false;
}) })
... ...
``` ```
...@@ -807,12 +893,17 @@ Badge({ ...@@ -807,12 +893,17 @@ Badge({
```ts ```ts
class dataTmp{
dataSource:IDataSource|undefined = undefined
}
let ds:dataTmp = new dataTmp()
List() { List() {
LazyForEach(this.dataSource, item => { if(ds.dataSource){
LazyForEach(ds.dataSource, () => {
ListItem() { ListItem() {
...
} }
}) })
}
}.cachedCount(3) }.cachedCount(3)
``` ```
......
...@@ -19,7 +19,7 @@ Swiper作为一个容器组件,在自身尺寸属性未被设置时,会自 ...@@ -19,7 +19,7 @@ Swiper作为一个容器组件,在自身尺寸属性未被设置时,会自
```ts ```ts
... ...
private swiperController: SwiperController = new SwiperController() export let swiperController: SwiperController = new SwiperController()
... ...
Swiper(this.swiperController) { Swiper(this.swiperController) {
Text("0") Text("0")
...@@ -156,6 +156,7 @@ Swiper(this.swiperController) { ...@@ -156,6 +156,7 @@ Swiper(this.swiperController) {
自定义导航点样式(示例:导航点直径设为30VP,左边距为0,导航点颜色设为红色): 自定义导航点样式(示例:导航点直径设为30VP,左边距为0,导航点颜色设为红色):
```ts ```ts
let swco:Record<string,number|Color> = {'size':30,'left':0,'color':Color.Red}
Swiper(this.swiperController) { Swiper(this.swiperController) {
Text("0") Text("0")
.width('90%') .width('90%')
...@@ -178,11 +179,7 @@ Swiper(this.swiperController) { ...@@ -178,11 +179,7 @@ Swiper(this.swiperController) {
.textAlign(TextAlign.Center) .textAlign(TextAlign.Center)
.fontSize(30) .fontSize(30)
} }
.indicatorStyle({ .indicatorStyle(swco)
size: 30,
left: 0,
color: Color.Red
})
``` ```
![ind](figures/ind.PNG) ![ind](figures/ind.PNG)
......
...@@ -159,13 +159,14 @@ ...@@ -159,13 +159,14 @@
```ts ```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.Start }) { Flex({ justifyContent: FlexAlign.Start }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C) Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding({ top: 10, bottom: 10 }) .padding(PTopBottom)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -175,13 +176,14 @@ ...@@ -175,13 +176,14 @@
```ts ```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.Center }) { Flex({ justifyContent: FlexAlign.Center }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C) Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding({ top: 10, bottom: 10 }) .padding(PTopBottom)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -191,13 +193,14 @@ ...@@ -191,13 +193,14 @@
```ts ```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.End }) { Flex({ justifyContent: FlexAlign.End }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C) Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding({ top: 10, bottom: 10 }) .padding(PTopBottom)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -207,13 +210,14 @@ ...@@ -207,13 +210,14 @@
```ts ```ts
let PTopBottom1:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.SpaceBetween }) { Flex({ justifyContent: FlexAlign.SpaceBetween }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C) Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding({ top: 10, bottom: 10 }) .padding(PTopBottom1)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -223,13 +227,14 @@ ...@@ -223,13 +227,14 @@
```ts ```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.SpaceAround }) { Flex({ justifyContent: FlexAlign.SpaceAround }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C) Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding({ top: 10, bottom: 10 }) .padding(PTopBottom)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -239,13 +244,14 @@ ...@@ -239,13 +244,14 @@
```ts ```ts
let PTopBottom:Record<string,number> = { 'top': 10, 'bottom': 10 }
Flex({ justifyContent: FlexAlign.SpaceEvenly }) { Flex({ justifyContent: FlexAlign.SpaceEvenly }) {
Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
Text('2').width('20%').height(50).backgroundColor(0xD2B48C) Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding({ top: 10, bottom: 10 }) .padding(PTopBottom)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -266,12 +272,13 @@ ...@@ -266,12 +272,13 @@
```ts ```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Auto }) { Flex({ alignItems: ItemAlign.Auto }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C) Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
} }
.size({ width: '90%', height: 80 }) .size(SWh)
.padding(10) .padding(10)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -282,12 +289,13 @@ ...@@ -282,12 +289,13 @@
```ts ```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Start }) { Flex({ alignItems: ItemAlign.Start }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C) Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
} }
.size({ width: '90%', height: 80 }) .size(SWh)
.padding(10) .padding(10)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -298,12 +306,13 @@ ...@@ -298,12 +306,13 @@
```ts ```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Center }) { Flex({ alignItems: ItemAlign.Center }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C) Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
} }
.size({ width: '90%', height: 80 }) .size(SWh)
.padding(10) .padding(10)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -314,12 +323,13 @@ ...@@ -314,12 +323,13 @@
```ts ```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.End }) { Flex({ alignItems: ItemAlign.End }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C) Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
} }
.size({ width: '90%', height: 80 }) .size(SWh)
.padding(10) .padding(10)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -330,12 +340,13 @@ ...@@ -330,12 +340,13 @@
```ts ```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Stretch }) { Flex({ alignItems: ItemAlign.Stretch }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C) Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
} }
.size({ width: '90%', height: 80 }) .size(SWh)
.padding(10) .padding(10)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
...@@ -346,12 +357,13 @@ ...@@ -346,12 +357,13 @@
```ts ```ts
let SWh:Record<string,number|string> = { 'width': '90%', 'height': 80 }
Flex({ alignItems: ItemAlign.Baseline }) { Flex({ alignItems: ItemAlign.Baseline }) {
Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) Text('1').width('33%').height(30).backgroundColor(0xF5DEB3)
Text('2').width('33%').height(40).backgroundColor(0xD2B48C) Text('2').width('33%').height(40).backgroundColor(0xD2B48C)
Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)
} }
.size({ width: '90%', height: 80 }) .size(SWh)
.padding(10) .padding(10)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
......
...@@ -73,7 +73,7 @@ GridRow({ ...@@ -73,7 +73,7 @@ GridRow({
reference: BreakpointsReference.WindowSize reference: BreakpointsReference.WindowSize
} }
}) { }) {
ForEach(this.bgColors, (color, index) => { ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ GridCol({
span: { span: {
xs: 2, xs: 2,
...@@ -106,12 +106,14 @@ GridRow中通过columns设置栅格布局的总列数。 ...@@ -106,12 +106,14 @@ GridRow中通过columns设置栅格布局的总列数。
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]; @State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
... ...
GridRow() { GridRow() {
ForEach(this.bgColors, (item, index) => { ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
if(index){
GridCol() { GridCol() {
Row() { Row() {
Text(`${index + 1}`) Text(`${index + 1}`)
}.width('100%').height('50') }.width('100%').height('50')
}.backgroundColor(item) }.backgroundColor(item)
}
}) })
} }
``` ```
...@@ -122,45 +124,58 @@ GridRow中通过columns设置栅格布局的总列数。 ...@@ -122,45 +124,58 @@ GridRow中通过columns设置栅格布局的总列数。
```ts ```ts
class CurrTmp{
currentBp: string = 'unknown';
set(val:string){
this.currentBp = val
}
}
let BorderWH:Record<string,Color|number> = { 'color': Color.Blue, 'width': 2 }
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]; @State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
@State currentBp: string = 'unknown'; @State currentBp: string = 'unknown';
... ...
Row() { Row() {
GridRow({ columns: 4 }) { GridRow({ columns: 4 }) {
ForEach(this.bgColors, (item, index) => { ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
if(index){
GridCol() { GridCol() {
Row() { Row() {
Text(`${index + 1}`) Text(`${index.toString() + 1}`)
}.width('100%').height('50') }.width('100%').height('50')
}.backgroundColor(item) }.backgroundColor(item)
}
}) })
} }
.width('100%').height('100%') .width('100%').height('100%')
.onBreakpointChange((breakpoint) => { .onBreakpointChange((breakpoint:string) => {
this.currentBp = breakpoint let CurrSet:CurrTmp = new CurrTmp()
CurrSet.set(breakpoint)
}) })
} }
.height(160) .height(160)
.border({ color: Color.Blue, width: 2 }) .border(BorderWH)
.width('90%') .width('90%')
Row() { Row() {
GridRow({ columns: 8 }) { GridRow({ columns: 8 }) {
ForEach(this.bgColors, (item, index) => { ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
if(index){
GridCol() { GridCol() {
Row() { Row() {
Text(`${index + 1}`) Text(`${index.toString() + 1}`)
}.width('100%').height('50') }.width('100%').height('50')
}.backgroundColor(item) }.backgroundColor(item)
}
}) })
} }
.width('100%').height('100%') .width('100%').height('100%')
.onBreakpointChange((breakpoint) => { .onBreakpointChange((breakpoint:string) => {
this.currentBp = breakpoint let CurrSet:CurrTmp = new CurrTmp()
CurrSet.set(breakpoint)
}) })
} }
.height(160) .height(160)
.border({ color: Color.Blue, width: 2 }) .border(BorderWH)
.width('90%') .width('90%')
``` ```
...@@ -172,12 +187,14 @@ GridRow中通过columns设置栅格布局的总列数。 ...@@ -172,12 +187,14 @@ GridRow中通过columns设置栅格布局的总列数。
```ts ```ts
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown] @State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]
GridRow({ columns: { sm: 4, md: 8 }, breakpoints: { value: ['200vp', '300vp', '400vp', '500vp', '600vp'] } }) { GridRow({ columns: { sm: 4, md: 8 }, breakpoints: { value: ['200vp', '300vp', '400vp', '500vp', '600vp'] } }) {
ForEach(this.bgColors, (item, index) => { ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
if(index){
GridCol() { GridCol() {
Row() { Row() {
Text(`${index + 1}`) Text(`${index.toString() + 1}`)
}.width('100%').height('50') }.width('100%').height('50')
}.backgroundColor(item) }.backgroundColor(item)
}
}) })
} }
``` ```
...@@ -241,30 +258,33 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ...@@ -241,30 +258,33 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
```ts ```ts
let Gspan:Record<string,number> = { 'xs': 1, 'sm': 2, 'md': 3, 'lg': 4 }
GridCol({ span: 2 }){} GridCol({ span: 2 }){}
GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }){} GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }){}
GridCol(){}.span(2) GridCol(){}.span(2)
GridCol(){}.span({ xs: 1, sm: 2, md: 3, lg: 4 }) GridCol(){}.span(Gspan)
``` ```
- 设置offset。 - 设置offset。
```ts ```ts
let Goffset:Record<string,number> = { 'xs': 1, 'sm': 2, 'md': 3, 'lg': 4 }
GridCol({ offset: 2 }){} GridCol({ offset: 2 }){}
GridCol({ offset: { xs: 2, sm: 2, md: 2, lg: 2 } }){} GridCol({ offset: { xs: 2, sm: 2, md: 2, lg: 2 } }){}
GridCol(){}.offset(2) GridCol(){}.offset(2)
GridCol(){}.offset({ xs: 1, sm: 2, md: 3, lg: 4 }) GridCol(){}.offset(Goffset)
``` ```
- 设置order。 - 设置order。
```ts ```ts
let Gorder:Record<string,number> = { 'xs': 1, 'sm': 2, 'md': 3, 'lg': 4 }
GridCol({ order: 2 }){} GridCol({ order: 2 }){}
GridCol({ order: { xs: 1, sm: 2, md: 3, lg: 4 } }){} GridCol({ order: { xs: 1, sm: 2, md: 3, lg: 4 } }){}
GridCol(){}.order(2) GridCol(){}.order(2)
GridCol(){}.order({ xs: 1, sm: 2, md: 3, lg: 4 }) GridCol(){}.order(Gorder)
``` ```
...@@ -279,7 +299,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ...@@ -279,7 +299,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]; @State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
... ...
GridRow({ columns: 8 }) { GridRow({ columns: 8 }) {
ForEach(this.bgColors, (color, index) => { ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ span: 2 }) { GridCol({ span: 2 }) {
Row() { Row() {
Text(`${index}`) Text(`${index}`)
...@@ -299,7 +319,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ...@@ -299,7 +319,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]; @State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
... ...
GridRow({ columns: 8 }) { GridRow({ columns: 8 }) {
ForEach(this.bgColors, (color, index) => { ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) { GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) {
Row() { Row() {
Text(`${index}`) Text(`${index}`)
...@@ -324,7 +344,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ...@@ -324,7 +344,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]; @State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
... ...
GridRow() { GridRow() {
ForEach(this.bgColors, (color, index) => { ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ offset: 2 }) { GridCol({ offset: 2 }) {
Row() { Row() {
Text('' + index) Text('' + index)
...@@ -347,7 +367,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ...@@ -347,7 +367,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设
... ...
GridRow() { GridRow() {
ForEach(this.bgColors, (color, index) => { ForEach(this.bgColors, (color:Color, index?:number|undefined) => {
GridCol({ offset: { xs: 1, sm: 2, md: 3, lg: 4 } }) { GridCol({ offset: { xs: 1, sm: 2, md: 3, lg: 4 } }) {
Row() { Row() {
Text('' + index) Text('' + index)
......
...@@ -567,7 +567,8 @@ struct BlankExample { ...@@ -567,7 +567,8 @@ struct BlankExample {
build() { build() {
Scroll(this.scroller) { Scroll(this.scroller) {
Column() { Column() {
ForEach(this.arr, (item) => { ForEach(this.arr, (item?:number|undefined) => {
if(item){
Text(item.toString()) Text(item.toString())
.width('90%') .width('90%')
.height(150) .height(150)
...@@ -576,7 +577,8 @@ struct BlankExample { ...@@ -576,7 +577,8 @@ struct BlankExample {
.fontSize(16) .fontSize(16)
.textAlign(TextAlign.Center) .textAlign(TextAlign.Center)
.margin({ top: 10 }) .margin({ top: 10 })
}, item => item) }
}, ((item:string):string => item))
}.width('100%') }.width('100%')
} }
.backgroundColor(0xDCDCDC) .backgroundColor(0xDCDCDC)
...@@ -604,7 +606,8 @@ struct BlankExample { ...@@ -604,7 +606,8 @@ struct BlankExample {
build() { build() {
Scroll(this.scroller) { Scroll(this.scroller) {
Row() { Row() {
ForEach(this.arr, (item) => { ForEach(this.arr, (item?:number|undefined) => {
if(item){
Text(item.toString()) Text(item.toString())
.height('90%') .height('90%')
.width(150) .width(150)
...@@ -613,6 +616,7 @@ struct BlankExample { ...@@ -613,6 +616,7 @@ struct BlankExample {
.fontSize(16) .fontSize(16)
.textAlign(TextAlign.Center) .textAlign(TextAlign.Center)
.margin({ left: 10 }) .margin({ left: 10 })
}
}) })
}.height('100%') }.height('100%')
} }
......
...@@ -25,15 +25,15 @@ import mediaquery from '@ohos.mediaquery'; ...@@ -25,15 +25,15 @@ import mediaquery from '@ohos.mediaquery';
```ts ```ts
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); let listener:mediaquery = mediaquery.matchMediaSync('(orientation: landscape)');
``` ```
给条件监听句柄listener绑定回调函数onPortrait,当listener检测设备状态变化时执行回调函数。在回调函数内,根据不同设备状态更改页面布局或者实现业务逻辑。 给条件监听句柄listener绑定回调函数onPortrait,当listener检测设备状态变化时执行回调函数。在回调函数内,根据不同设备状态更改页面布局或者实现业务逻辑。
```ts ```ts
onPortrait(mediaQueryResult) { onPortrait(mediaQueryResult:mediaquery) {
if (mediaQueryResult.matches) { if (mediaQueryResult.matches as boolean) {
// do something here // do something here
} else { } else {
// do something here // do something here
...@@ -143,19 +143,18 @@ import mediaquery from '@ohos.mediaquery'; ...@@ -143,19 +143,18 @@ import mediaquery from '@ohos.mediaquery';
import window from '@ohos.window'; import window from '@ohos.window';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
let portraitFunc = null; export let portraitFunc:mediaquery.MediaQueryResult|void|null = null;
@Entry @Entry
@Component @Component
struct MediaQueryExample { struct MediaQueryExample {
@State color: string = '#DB7093'; @State color: string = '#DB7093';
@State text: string = 'Portrait'; @State text: string = 'Portrait';
// 当设备横屏时条件成立 // 当设备横屏时条件成立
listener = mediaquery.matchMediaSync('(orientation: landscape)'); listener:mediaquery = mediaquery.matchMediaSync('(orientation: landscape)');
// 当满足媒体查询条件时,触发回调 // 当满足媒体查询条件时,触发回调
onPortrait(mediaQueryResult) { onPortrait(mediaQueryResult:mediaquery) {
if (mediaQueryResult.matches) { // 若设备为横屏状态,更改相应的页面布局 if (mediaQueryResult.matches as boolean) { // 若设备为横屏状态,更改相应的页面布局
this.color = '#FFD700'; this.color = '#FFD700';
this.text = 'Landscape'; this.text = 'Landscape';
} else { } else {
...@@ -166,7 +165,7 @@ struct MediaQueryExample { ...@@ -166,7 +165,7 @@ struct MediaQueryExample {
aboutToAppear() { aboutToAppear() {
// 绑定当前应用实例 // 绑定当前应用实例
portraitFunc = this.onPortrait.bind(this); portraitFunc = this.onPortrait(this);
// 绑定回调函数 // 绑定回调函数
this.listener.on('change', portraitFunc); this.listener.on('change', portraitFunc);
} }
...@@ -174,7 +173,7 @@ struct MediaQueryExample { ...@@ -174,7 +173,7 @@ struct MediaQueryExample {
// 改变设备横竖屏状态函数 // 改变设备横竖屏状态函数
private changeOrientation(isLandscape: boolean) { private changeOrientation(isLandscape: boolean) {
// 获取UIAbility实例的上下文信息 // 获取UIAbility实例的上下文信息
let context = getContext(this) as common.UIAbilityContext; let context:common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
// 调用该接口手动改变设备横竖屏状态 // 调用该接口手动改变设备横竖屏状态
window.getLastWindow(context).then((lastWindow) => { window.getLastWindow(context).then((lastWindow) => {
lastWindow.setPreferredOrientation(isLandscape ? window.Orientation.LANDSCAPE : window.Orientation.PORTRAIT) lastWindow.setPreferredOrientation(isLandscape ? window.Orientation.LANDSCAPE : window.Orientation.PORTRAIT)
...@@ -205,17 +204,17 @@ FA模型下的示例: ...@@ -205,17 +204,17 @@ FA模型下的示例:
import mediaquery from '@ohos.mediaquery'; import mediaquery from '@ohos.mediaquery';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let portraitFunc = null; let portraitFunc:mediaquery.MediaQueryResult|void|null = null;
@Entry @Entry
@Component @Component
struct MediaQueryExample { struct MediaQueryExample {
@State color: string = '#DB7093'; @State color: string = '#DB7093';
@State text: string = 'Portrait'; @State text: string = 'Portrait';
listener = mediaquery.matchMediaSync('(orientation: landscape)'); // 当设备横屏时条件成立 listener:mediaquery = mediaquery.matchMediaSync('(orientation: landscape)'); // 当设备横屏时条件成立
onPortrait(mediaQueryResult) { // 当满足媒体查询条件时,触发回调 onPortrait(mediaQueryResult:mediaquery) { // 当满足媒体查询条件时,触发回调
if (mediaQueryResult.matches) { // 若设备为横屏状态,更改相应的页面布局 if (mediaQueryResult.matches as boolean) { // 若设备为横屏状态,更改相应的页面布局
this.color = '#FFD700'; this.color = '#FFD700';
this.text = 'Landscape'; this.text = 'Landscape';
} else { } else {
...@@ -225,7 +224,7 @@ struct MediaQueryExample { ...@@ -225,7 +224,7 @@ struct MediaQueryExample {
} }
aboutToAppear() { aboutToAppear() {
portraitFunc = this.onPortrait.bind(this); // 绑定当前应用实例 portraitFunc = this.onPortrait(this); // 绑定当前应用实例
this.listener.on('change', portraitFunc); //绑定回调函数 this.listener.on('change', portraitFunc); //绑定回调函数
} }
...@@ -234,12 +233,12 @@ struct MediaQueryExample { ...@@ -234,12 +233,12 @@ struct MediaQueryExample {
Text(this.text).fontSize(50).fontColor(this.color) Text(this.text).fontSize(50).fontColor(this.color)
Text('Landscape').fontSize(50).fontColor(this.color).backgroundColor(Color.Orange) Text('Landscape').fontSize(50).fontColor(this.color).backgroundColor(Color.Orange)
.onClick(() => { .onClick(() => {
let context = featureAbility.getContext(); let context:featureAbility = featureAbility.getContext();
context.setDisplayOrientation(0); //调用该接口手动改变设备横竖屏状态 context.setDisplayOrientation(0); //调用该接口手动改变设备横竖屏状态
}) })
Text('Portrait').fontSize(50).fontColor(this.color).backgroundColor(Color.Orange) Text('Portrait').fontSize(50).fontColor(this.color).backgroundColor(Color.Orange)
.onClick(() => { .onClick(() => {
let context = featureAbility.getContext(); let context:featureAbility = featureAbility.getContext();
context.setDisplayOrientation(1); //调用该接口手动改变设备横竖屏状态 context.setDisplayOrientation(1); //调用该接口手动改变设备横竖屏状态
}) })
} }
......
...@@ -35,24 +35,25 @@ ...@@ -35,24 +35,25 @@
- RelativeContainer父组件为锚点,__container__代表父容器的id。 - RelativeContainer父组件为锚点,__container__代表父容器的id。
```ts ```ts
let AlignRus:Record<string,Record<string,string|VerticalAlign|HorizontalAlign>> = {
'top': { 'anchor': '__container__', 'align': VerticalAlign.Top },
'left': { 'anchor': '__container__', 'align': HorizontalAlign.Start }
}
let AlignRue:Record<string,Record<string,string|VerticalAlign|HorizontalAlign>> = {
'top': { 'anchor': '__container__', 'align': VerticalAlign.Top },
'left': { 'anchor': '__container__', 'align': HorizontalAlign.End }
}
RelativeContainer() { RelativeContainer() {
Row() Row()
// 添加其他属性 // 添加其他属性
.alignRules({ .alignRules(AlignRus)
top: { anchor: '__container__', align: VerticalAlign.Top },
left: { anchor: '__container__', align: HorizontalAlign.Start }
})
.id("row1") .id("row1")
Row() Row()
... ...
.alignRules({ .alignRules(AlignRue)
top: { anchor: '__container__', align: VerticalAlign.Top },
right: { anchor: '__container__', align: HorizontalAlign.End }
})
.id("row2") .id("row2")
} }
...
``` ```
![zh-cn_image_0000001562820901](figures/zh-cn_image_0000001562820901.png) ![zh-cn_image_0000001562820901](figures/zh-cn_image_0000001562820901.png)
...@@ -60,14 +61,15 @@ ...@@ -60,14 +61,15 @@
- 以子元素为锚点。 - 以子元素为锚点。
```ts ```ts
RelativeContainer() { let RelConB:Record<string,Record<string,string|VerticalAlign|HorizontalAlign>> = {
... 'top': { 'anchor': 'row1', 'align': VerticalAlign.Bottom }
top: { anchor: 'row1', align: VerticalAlign.Bottom },
...
} }
let Mleft:Record<string,number> = { 'left': 20 }
let BWC:Record<string,number|string> = { 'width': 2, 'color': '#6699FF' }
RelativeContainer() {RelConB}
.width(300).height(300) .width(300).height(300)
.margin({ left: 20 }) .margin(Mleft)
.border({ width: 2, color: '#6699FF' }) .border(BWC)
``` ```
![zh-cn_image_0000001562940613](figures/zh-cn_image_0000001562940613.png) ![zh-cn_image_0000001562940613](figures/zh-cn_image_0000001562940613.png)
......
...@@ -22,12 +22,13 @@ Stack组件为容器组件,容器内可包含各种子组件。其中的子组 ...@@ -22,12 +22,13 @@ Stack组件为容器组件,容器内可包含各种子组件。其中的子组
```ts ```ts
let MTop:Record<string,number> = { 'top': 50 }
Column(){ Column(){
Stack({ }) { Stack({ }) {
Column(){}.width('90%').height('100%').backgroundColor('#ff58b87c') Column(){}.width('90%').height('100%').backgroundColor('#ff58b87c')
Text('text').width('60%').height('60%').backgroundColor('#ffc3f6aa') Text('text').width('60%').height('60%').backgroundColor('#ffc3f6aa')
Button('button').width('30%').height('30%').backgroundColor('#ff8ff3eb').fontColor('#000') Button('button').width('30%').height('30%').backgroundColor('#ff8ff3eb').fontColor('#000')
}.width('100%').height(150).margin({ top: 50 }) }.width('100%').height(150).margin(MTop)
} }
``` ```
...@@ -51,6 +52,7 @@ Stack容器中兄弟组件显示层级关系可以通过[Z序控制](../referenc ...@@ -51,6 +52,7 @@ Stack容器中兄弟组件显示层级关系可以通过[Z序控制](../referenc
在层叠布局中,如果后面子元素尺寸大于前面子元素尺寸,则前面子元素完全隐藏。 在层叠布局中,如果后面子元素尺寸大于前面子元素尺寸,则前面子元素完全隐藏。
```ts ```ts
let MTopM1:Record<string,number> = { 'top': 100 }
Stack({ alignContent: Alignment.BottomStart }) { Stack({ alignContent: Alignment.BottomStart }) {
Column() { Column() {
Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20) Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20)
...@@ -63,7 +65,7 @@ Stack({ alignContent: Alignment.BottomStart }) { ...@@ -63,7 +65,7 @@ Stack({ alignContent: Alignment.BottomStart }) {
Column() { Column() {
Text('Stack子元素3').fontSize(20) Text('Stack子元素3').fontSize(20)
}.width(200).height(200).backgroundColor(Color.Grey) }.width(200).height(200).backgroundColor(Color.Grey)
}.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0) }.margin(MTopM1).width(350).height(350).backgroundColor(0xe0e0e0)
``` ```
![zh-cn_image_0000001511900544](figures/zh-cn_image_0000001511900544.png) ![zh-cn_image_0000001511900544](figures/zh-cn_image_0000001511900544.png)
...@@ -72,6 +74,7 @@ Stack({ alignContent: Alignment.BottomStart }) { ...@@ -72,6 +74,7 @@ Stack({ alignContent: Alignment.BottomStart }) {
```ts ```ts
let MTopM:Record<string,number> = { 'top': 100 }
Stack({ alignContent: Alignment.BottomStart }) { Stack({ alignContent: Alignment.BottomStart }) {
Column() { Column() {
Text('Stack子元素1').fontSize(20) Text('Stack子元素1').fontSize(20)
...@@ -84,7 +87,7 @@ Stack({ alignContent: Alignment.BottomStart }) { ...@@ -84,7 +87,7 @@ Stack({ alignContent: Alignment.BottomStart }) {
Column() { Column() {
Text('Stack子元素3').fontSize(20) Text('Stack子元素3').fontSize(20)
}.width(200).height(200).backgroundColor(Color.Grey) }.width(200).height(200).backgroundColor(Color.Grey)
}.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0) }.margin(MTopM).width(350).height(350).backgroundColor(0xe0e0e0)
``` ```
![zh-cn_image_0000001563060797](figures/zh-cn_image_0000001563060797.png) ![zh-cn_image_0000001563060797](figures/zh-cn_image_0000001563060797.png)
...@@ -104,7 +107,7 @@ struct StackSample { ...@@ -104,7 +107,7 @@ struct StackSample {
build() { build() {
Stack({ alignContent: Alignment.Bottom }) { Stack({ alignContent: Alignment.Bottom }) {
Flex({ wrap: FlexWrap.Wrap }) { Flex({ wrap: FlexWrap.Wrap }) {
ForEach(this.arr, (item) => { ForEach(this.arr, (item:string) => {
Text(item) Text(item)
.width(100) .width(100)
.height(100) .height(100)
...@@ -113,7 +116,7 @@ struct StackSample { ...@@ -113,7 +116,7 @@ struct StackSample {
.textAlign(TextAlign.Center) .textAlign(TextAlign.Center)
.borderRadius(10) .borderRadius(10)
.backgroundColor(0xFFFFFF) .backgroundColor(0xFFFFFF)
}, item => item) }, ((item:string):string => item))
}.width('100%').height('100%') }.width('100%').height('100%')
Flex({ justifyContent: FlexAlign.SpaceAround, alignItems: ItemAlign.Center }) { Flex({ justifyContent: FlexAlign.SpaceAround, alignItems: ItemAlign.Center }) {
......
...@@ -38,6 +38,12 @@ ...@@ -38,6 +38,12 @@
3. 通过模态接口调起模态展示界面,通过转场动画或者共享元素动画去实现对应的动画效果。 3. 通过模态接口调起模态展示界面,通过转场动画或者共享元素动画去实现对应的动画效果。
```ts ```ts
class PresentTmp{
isPresent: boolean = false;
set(){
this.isPresent = !this.isPresent;
}
}
// 模态转场控制变量 // 模态转场控制变量
@State isPresent: boolean = false; @State isPresent: boolean = false;
...@@ -46,7 +52,8 @@ ...@@ -46,7 +52,8 @@
.bindContentCover($$this.isPresent, this.MyBuilder, ModalTransition.None) .bindContentCover($$this.isPresent, this.MyBuilder, ModalTransition.None)
.onClick(() => { .onClick(() => {
// 改变状态变量,让模态界面显示 // 改变状态变量,让模态界面显示
this.isPresent = !this.isPresent; let setPre:PresentTmp = new PresentTmp()
setPre.set()
}) })
``` ```
...@@ -147,7 +154,7 @@ struct BindContentCoverDemo { ...@@ -147,7 +154,7 @@ struct BindContentCoverDemo {
struct BindSheetDemo { struct BindSheetDemo {
// 半模态转场高度控制变量 // 半模态转场高度控制变量
@State sheetHeight: number = 300; @State sheetHeight: number|SheetSize|null|undefined = 300;
// 半模态转场控制条控制变量 // 半模态转场控制条控制变量
@State showDragBar: boolean = true; @State showDragBar: boolean = true;
...@@ -190,6 +197,7 @@ struct BindSheetDemo { ...@@ -190,6 +197,7 @@ struct BindSheetDemo {
build() { build() {
Column() { Column() {
if(this.sheetHeight){
Button("Click to present sheet view") Button("Click to present sheet view")
.onClick(() => { .onClick(() => {
// 改变状态变量,让模态界面显示 // 改变状态变量,让模态界面显示
...@@ -200,6 +208,7 @@ struct BindSheetDemo { ...@@ -200,6 +208,7 @@ struct BindSheetDemo {
// 通过选定的半模态接口,绑定模态展示界面,style中包含两个参数,一个是设置半模态的高度,不设置时默认高度是Large,一个是是否显示控制条DragBar,默认是true显示控制条 // 通过选定的半模态接口,绑定模态展示界面,style中包含两个参数,一个是设置半模态的高度,不设置时默认高度是Large,一个是是否显示控制条DragBar,默认是true显示控制条
.bindSheet($$this.isPresent, this.myBuilder(), { height: this.sheetHeight, dragBar: this.showDragBar }) .bindSheet($$this.isPresent, this.myBuilder(), { height: this.sheetHeight, dragBar: this.showDragBar })
} }
}
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
.width('100%') .width('100%')
.height('100%') .height('100%')
...@@ -216,6 +225,10 @@ struct BindSheetDemo { ...@@ -216,6 +225,10 @@ struct BindSheetDemo {
```ts ```ts
class BMD{
value:string = ''
action:Function|undefined = undefined
}
@Entry @Entry
@Component @Component
struct BindMenuDemo { struct BindMenuDemo {
...@@ -227,13 +240,13 @@ struct BindMenuDemo { ...@@ -227,13 +240,13 @@ struct BindMenuDemo {
action: () => { action: () => {
console.info('handle Menu1 select') console.info('handle Menu1 select')
} }
}, } as BMD,
{ {
value: '菜单项2', value: '菜单项2',
action: () => { action: () => {
console.info('handle Menu2 select') console.info('handle Menu2 select')
} }
}, } as BMD,
] ]
build() { build() {
...@@ -271,7 +284,8 @@ struct BindContextMenuDemo { ...@@ -271,7 +284,8 @@ struct BindContextMenuDemo {
@Builder MyMenu() { @Builder MyMenu() {
Row() { Row() {
Column() { Column() {
ForEach(this.num, (item: number, index: number) => { ForEach(this.num, (item: number, index?: number|undefined) => {
if(index){
Row() { Row() {
Text(item.toString()) Text(item.toString())
.fontSize(20) .fontSize(20)
...@@ -281,6 +295,7 @@ struct BindContextMenuDemo { ...@@ -281,6 +295,7 @@ struct BindContextMenuDemo {
.width('100%') .width('100%')
.aspectRatio(2) .aspectRatio(2)
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
}
}) })
} }
.width('100%') .width('100%')
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册