harmony 鸿蒙Using the Mirroring Capability

  • 2025-06-12
  • 浏览 (5)

Using the Mirroring Capability

Overview

To accommodate diverse user reading habits, ArkUI provides a mirroring capability that can reverse the display content along the x-axis, switching the layout from left-to-right to right-to-left.

Before Mirroring After Mirroring

The mirroring capability is activated on a component under either of these conditions:

  1. The component’s direction attribute is set to Direction.Rtl.

  2. The component’s direction attribute is set to Direction.Auto, and the system language in use (such as Uyghur) is read from right to left.

Basic Concepts

  • LTR: left-to-right reading direction
  • RTL: right-to-Left reading direction

Constraints

ArkUI has default mirroring support for the following capabilities:

Category Name
Basic components Swiper, Tabs, TabContent, List, Progress, CalendarPicker, CalendarPickerDialog, TextPicker, TextPickerDialog, DatePicker, DatePickerDialog, Grid, WaterFlow, Scroll, ScrollBar, AlphabetIndexer, Stepper, SideBarContainer, Navigation, NavDestination, Rating, Slider, Toggle, Badge, Counter, Chip, SegmentButton, bindMenu, bindContextMenu, TextInput, TextArea, Search, Stack, GridRow, Text, Select, Marquee, Row, Column, Flex, RelativeContainer, ListItemGroup
Advanced components SelectionMenu , TreeView , Filter, SplitLayout, ToolBar, ComposeListItem, EditableTitleBar, ProgressButton, SubHeader , Popup, Dialog, SwipeRefresher
Universal attributes position, markAnchor, offset, alignRules, borderWidth, borderColor, borderRadius, padding, margin
APIs AlertDialog, ActionSheet, promptAction.showDialog, promptAction.showToast

However, adaptation is still required in the following three scenarios:

  1. For layout and border settings, use the generalized direction terms start and end as parameter types instead of absolute terms such as left, right, x, and y, to accommodate mirroring.

  2. The Canvas component offers limited support for mirroring in text drawing only.

  3. The XComponent component does not support mirroring capabilities.

Layout and Border Settings

To adapt to mirroring capabilities, update the following universal attributes with new parameter types:

Position settings: position, markAnchor, offset, alignRules

Border settings: borderWidth, borderColor, borderRadius

Size settings: padding, margin

For example, with position, change the absolute directional descriptions of x and y to the new parameter types of start and end.

import { LengthMetrics } from '@kit.ArkUI';

@Entry
@Component
struct Index1 {
  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      Stack({ alignContent: Alignment.TopStart }) {
        Column()
          .width(100)
          .height(100)
          .backgroundColor(Color.Red)
          .position({ start: LengthMetrics.px(200), top: LengthMetrics.px(200) })  // Use the new LocalizedEdges parameter type added since API version 12 for supporting both LTR and RTL.
                                                                                   // It is equivalent to .position({ x: '200px', y: '200px' }) when only LTR is supported.

      }.backgroundColor(Color.Blue)
    }.width("100%").height("100%").border({ color: '#880606' })
  }
}

Custom Drawing with the Canvas Component

The drawings and coordinates of the Canvas component do not support mirroring. Content drawn on it does not automatically mirror when the system language changes.

CanvasRenderingContext2D supports mirroring for text rendering, which should be used with the Canvas component’s direction attribute and the direction attribute of CanvasRenderingContext2D. The specific specifications are as follows:

  1. Priority: The direction attribute of CanvasRenderingContext2D takes precedence over the Canvas component’s direction attribute, which in turn follows the system language’s horizontal display direction.
  2. The Canvas component does not automatically mirror with system language changes; applications must listen for system language changes and redraw the content on their own.
  3. Only symbols follow the direction setting during text drawing with CanvasRenderingContext2D; Latin characters and numbers do not.
import { BusinessError, commonEventManager } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  @State message: string = 'Hello world';
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)

  aboutToAppear(): void {
    // Listen for the system language changes.
    let subscriber: commonEventManager.CommonEventSubscriber|null = null;
    let subscribeInfo2: commonEventManager.CommonEventSubscribeInfo = {
      events: ["usual.event.LOCALE_CHANGED"],
    }
    commonEventManager.createSubscriber(subscribeInfo2, (err: BusinessError, data: commonEventManager.CommonEventSubscriber) => {
      if (err) {
        console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
        return;
      }

      subscriber = data;
      if (subscriber !== null) {
        commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
          if (err) {
            console.error(`Failed to subscribe to the language and region status change event. Code: ${err.code}; message: ${err.message}`);
            return;
          }
          console.info('Successfully subscribed to the language and region status change event: data: ' + JSON.stringify(data))
          // After detecting the language switch, redraw the content on the Canvas component.
          this.drawText();
        })
      } else {
        console.error(`MayTest Need create subscriber`);
      }
    })
  }

  drawText(): void {
    console.error("MayTest drawText")
    this.context.reset()
    this.context.direction = "inherit"
    this.context.font = '30px sans-serif'
    this.context.fillText("ab%123&*@", 50, 50)
  }

  build() {
    Row() {
      Canvas(this.context)
        .direction(Direction.Auto)
        .width("100%")
        .height("100%")
        .onReady(() =>{
          this.drawText()
        })
        .backgroundColor(Color.Pink)
    }
    .height('100%')
  }

}
Before Mirroring After Mirroring

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkUI

harmony 鸿蒙Atomic Service Full Screen Launch Component (FullScreenLaunchComponent)

harmony 鸿蒙Arc Button (ArcButton)

harmony 鸿蒙Animation Smoothing

harmony 鸿蒙Animation Overview

harmony 鸿蒙Frame Animation (ohos.animator)

harmony 鸿蒙Implementing Property Animation

harmony 鸿蒙Property Animation Overview

harmony 鸿蒙Dialog Box Overview

harmony 鸿蒙Blur Effect

0  赞