openharmony 鸿蒙 ohos-file-PhotoPickerComponent

2025-06-12 浏览 (1)

@ohos.file.PhotoPickerComponent (PhotoPickerComponent)

The PhotoPickerComponent embedded in the UI of an application allows the application to access images or videos in the user directory without any permission. This component grants the application only the read permission. The user can directly tap this component to select images or videos.

NOTE

This component is supported since API version 12. Updates will be marked with a superscript to indicate their earliest API version.

Modules to Import

import {
  PhotoPickerComponent, PickerController, PickerOptions,
  DataType, BaseItemInfo, ItemInfo, PhotoBrowserInfo, AnimatorParams,
  MaxSelected, ItemType, ClickType, PickerOrientation,
  SelectMode, PickerColorMode, ReminderMode, MaxCountType, PhotoBrowserRange, PhotoBrowserUIElement,
  ItemsDeletedCallback, ExceedMaxSelectedCallback, CurrentAlbumDeletedCallback
} from '@ohos.file.PhotoPickerComponent';

Properties

The universal properties are supported.

PhotoPickerComponent

PhotoPickerComponent({ pickerOptions?: PickerOptions, onSelect?: (uri: string) => void, onDeselect?: (uri: string) => void, onItemClicked?: (itemInfo: ItemInfo, clickType: ClickType) => boolean, onEnterPhotoBrowser?: (photoBrowserInfo: PhotoBrowserInfo) => boolean, onExitPhotoBrowser?: (photoBrowserInfo: PhotoBrowserInfo) => boolean, onPickerControllerReady?: () => void, onPhotoBrowserChanged?: (browserItemInfo: BaseItemInfo) => boolean, onSelectedItemsDeleted?: ItemsDeletedCallback, onExceedMaxSelected?: ExceedMaxSelectedCallback, onCurrentAlbumDeleted?: CurrentAlbumDeletedCallback, pickerController: PickerController })

Allows the application to access images or videos in the user directory without any permission.

NOTE

If the PhotoPickerComponent is used with the Tabs component, the swipe gestures of the Tabs component conflict with those of the photo browser page. To prevent this problem, you can disable the swipe operation for the Tabs component in onEnterPhotoBrowser() and enable it in onExitPhotoBrowser(). This conflict will be resolved in later versions.

Decorator: @Component

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDecorator DescriptionDescription
pickerOptionsPickerOptionsNo-Configuration of Picker.
onSelect(uri: string) => voidNo-Callback to be invoked when an image is selected by using PhotoPickerComponent. This callback returns the URI of the image selected to the application.
onDeselect(uri: string) => voidNo-Callback to be invoked when an image is deselected by using PhotoPickerComponent. This callback returns the URI of the image deselected to the application.
onItemClicked(itemInfo: ItemInfo, clickType: ClickType) => booleanNo-Callback to be invoked when an item in a PhotoPickerComponent is clicked.
For an image (thumbnail item), if true is returned, the image is selected. Otherwise, the image is not selected and the URI is not granted with the permission. For a camera item, if true is returned, the system camera is started. Otherwise, the camera is not started and the application handles the request.
onEnterPhotoBrowser(photoBrowserInfo: PhotoBrowserInfo) => booleanNo-Callback to be invoked when the photo browser page is displayed. The callback returns photo browser information to the application.
onExitPhotoBrowser(photoBrowserInfo: PhotoBrowserInfo) => booleanNo-Callback to be invoked when the photo browser page exits. The callback returns photo browser information to the application.
onPickerControllerReady() => voidNo-Callback to be invoked when pickerController is available.
The PickerController APIs can be called only after this callback is invoked.
onPhotoBrowserChanged(browserItemInfo: BaseItemInfo) => booleanNo-Callback to be invoked when the photo browser page is swiped left or right. The callback returns photo browser information to the application.
onSelectedItemsDeleted13+ItemsDeletedCallbackNo-Callback to be invoked when the selected items are deleted. This callback returns information about the deleted items to the application.
onExceedMaxSelected13+ExceedMaxSelectedCallbackNo-Callback to be invoked when the number of selected media assets exceeds the limit (maximum number of selected images, selected videos, or selected items).
- If the number of selected images reaches the maximum but does not reach the maximum count of selected items, exceedMaxCountType in the callback is MaxCountType.PHOTO_MAX_COUNT.
- If the number of selected videos reaches the maximum but does not reach the maximum count of selected items, exceedMaxCountType in the callback is MaxCountType.VIDEO_MAX_COUNT.
- If the number of selected media assets reaches the maximum count of selected items, exceedMaxCountType in the callback is MaxCountType.TOTAL_MAX_COUNT.
onCurrentAlbumDeleted13+CurrentAlbumDeletedCallbackNo-Callback to be invoked when the current album is deleted.
The album is specified by currentAlbumUri in pickerController.setData(DataType.SET_ALBUM_URI, currentAlbumUri).
To refresh the grid page to display the default album after the current album is deleted, you can set the title bar name to the default album name, for example, Photos and videos, Photos, or Videos, and call pickerController.setData(DataType.SET_ALBUM_URI, '') with an empty string.
onVideoPlayStateChanged14+videoPlayStateChangedCallbackNo-Callback to be invoked when the video playback state on a photo browser page changes.
pickerControllerPickerControllerNo@ObjectLinkInstance used to send data to the PhotoPickerComponent.

PickerOptions

Defines the configuration of Picker. It inherits from BaseSelectOptions.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
checkBoxColorstringNoBackground color of the check box. The value is an 8-digit hexadecimal color code.
backgroundColorstringNoBackground color of the Picker grid page. The value is an 8-digit hexadecimal color code.
isRepeatSelectSupportedbooleanNoWhether to support repeat selection of a single image. The value true means that a single image can be repeatedly selected. The default value is false.
checkboxTextColorstringNoText color in the check box. The value is an 8-digit hexadecimal color code. (This capability is not supported currently.)
photoBrowserBackgroundColorModePickerColorModeNoBackground color of the photo browser page. The options are AUTO, LIGHT, and DARK. The default value is AUTO.
maxSelectedReminderModeReminderModeNoMode of the reminder when the number of selected items reaches the maximum. The options are NONE, TOAST, and MASK. The default value TOAST.
orientationPickerOrientationNoSliding preview direction of the grid page. The options are HORIZONTAL and VERTICAL. The default value is VERTICAL.
selectModeSelectModeNoSelect mode, which can be SINGLE_SELECT or MULTI_SELECT. The default value is MULTI_SELECT.
maxPhotoSelectNumbernumberNoMaximum number of images that can be selected. The maximum value is 500, which is limited by MaxSelected. The default value is 500.
maxVideoSelectNumbernumberNoMaximum number of videos that can be selected. The maximum value is 500, which is limited by MaxSelected. The default value is 500.
isSlidingSelectionSupported13+booleanNoWhether sliding selection (selecting multiple items by sliding finger across the screen) is supported. The value true means that sliding selection is supported. By default, it is not supported. This parameter is not available for repeat selection.
photoBrowserCheckboxPosition13+[number, number]NoPosition of the check box on the photo browser page. The first parameter specifies the offset in the X direction, and the second parameter specifies the offset in the Y direction. The value range is 0-1, which indicates the offset (from 0% to 100%) to the upper left corner of the component. The default value is [0, 0].
gridMargin14+MarginNoMargin of the component on a grid page.
photoBrowserMargin14+MarginNoMargin of the component on a photo browser page.
singleLineConfig20+SingleLineConfigNoSingle-line display mode of the component on the grid page. In single-line mode, the component does not provide functions for viewing a larger image. The component does not support callbacks related to large images, and the PickerController does not support APIs related to large images, making API calls ineffective.

ItemsDeletedCallback13+

type ItemsDeletedCallback = (baseItemInfos: Array<BaseItemInfo>) => void

Called when the selected items are deleted.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
baseItemInfosArray<BaseItemInfo>YesBasic information about the selected items.

ExceedMaxSelectedCallback13+

type ExceedMaxSelectedCallback = (exceedMaxCountType: MaxCountType) => void

Called when items are selected after the maximum count has been reached.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
exceedMaxCountTypeMaxCountTypeYesType of the maximum count that has been reached. It can be the maximum count of selected images, maximum count of selected videos, or maximum count of selected images and videos.

CurrentAlbumDeletedCallback13+

type CurrentAlbumDeletedCallback = () => void

Called when the current album is deleted.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

videoPlayStateChangedCallback14+

type videoPlayStateChangedCallback = (state: VideoPlayerState) => void

Callback to be invoked when the video playback state on a photo browser page changes.

Atomic service API: This API can be used in atomic services since API version 14.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

PickerController

Defines an instance used to send data to the PhotoPickerComponent.

Decorator Type: @Observed

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

setData

setData(dataType: DataType, data: Object): void

Sends data of the specified type to PhotoPickerComponent.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
dataTypeDataTypeYesType of the data to send.
dataObjectYesData to send.

setMaxSelected

setMaxSelected(maxSelected: MaxSelected): void

Sets the maximum number of images, videos, or images and videos that can be selected on a real-time basis.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
maxSelectedMaxSelectedYesMaximum number of media assets that can be selected at a time.

setPhotoBrowserItem

setPhotoBrowserItem(uri: string, photoBrowserRange?: PhotoBrowserRange): void

Switches from the PhotoPickerComponent to the photo browser page or from the photo browser page to the image to be viewed.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uristringYesURI of the image to view. Only the images selected by the user are supported.
photoBrowserRangePhotoBrowserRangeNoView range on the photo browser page. The value can be ALL or SELECTED_ONLY. The default value is ALL, which means to view all images and videos.

exitPhotoBrowser13+

exitPhotoBrowser(): void

Exits the photo browser page.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

setPhotoBrowserUIElementVisibility13+

setPhotoBrowserUIElementVisibility(elements: Array<PhotoBrowserUIElement>, isVisible: boolean): void

Sets whether other UI elements are visible on the photo browser page. By default, other UI elements are visible.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
elementsArray<PhotoBrowserUIElement>YesOther UI elements on the photo browser page.
isVisiblebooleanYesWhether the specified UI elements are visible. The value true means that they are visible. The default value is false.

replacePhotoPickerPreview15+

replacePhotoPickerPreview(originalUri: string, newUri: string, callback: AsyncCallback<void>): void

Replaces the image selected by the user in the PhotoPickerComponent with the image edited by the application.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
originalUristringYesURI of the original image, which will be replaced.
newUribooleanYesURI of the new image. The new image is temporarily stored in the application sandbox path. Therefore, this URI specifies a directory in the application sandbox path.
callbackAsyncCallback<void>YesCallback invoked when image replacement is complete.

saveTrustedPhotoAssets15+

saveTrustedPhotoAssets(trustedUris: Array<string>, callback: AsyncCallback<Array<string>>, configs?: Array<photoAccessHelper.PhotoCreationConfig>, saveMode?: SaveMode): void

Saves files in a URI list. Generally, this API is used together with replacePhotoPickerPreview to save the new images or videos in the application sandbox path to Gallery.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
trustedUrisArray<string>YesURIs of the images or videos in the application sandbox path. Generally, trustedUris comes from newUri of new images generated by replacePhotoPickerPreview.
callbackAsyncCallback<Array<string>>YesURIs of the new files in Gallery.
configsArray<photoAccessHelper.PhotoCreationConfig>NoConfiguration parameters corresponding to the original files.
saveModeSaveModeNoMode for saving the files.

BaseItemInfo

Represents basic image and video information.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
uristringNoImage or video URI. This parameter is mandatory when itemType is THUMBNAIL. Otherwise, it is left empty.
mimeTypestringNoMIME type of the image or video. This parameter is mandatory when itemType is THUMBNAIL. Otherwise, it is left empty.
widthnumberNoWidth of the image or video, in pixels. This parameter is mandatory when itemType is THUMBNAIL. Otherwise, it is left empty.
heightnumberNoHeight of the image or video, in pixels. This parameter is mandatory when itemType is THUMBNAIL. Otherwise, it is left empty.
sizenumberNoSize of the image or video, in kilobytes. This parameter is mandatory when itemType is THUMBNAIL. Otherwise, it is left empty.
durationnumberNoVideo duration, in ms. This parameter is mandatory when itemType is THUMBNAIL. Otherwise, it is left empty.
The value -1 indicates an image.

ItemInfo

Represents image and video information. It inherits from BaseItemInfo, adding the private parameter itemType.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
itemTypeItemTypeNoType of the item, which can be THUMBNAIL or CAMERA.

PhotoBrowserInfo

Represents information about the photo browser page.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
animatorParamsAnimatorParamsNoAnimation for entering or exiting the photo browser page.

AnimatorParams

Animation parameters for entering or exiting the photo browser page.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
durationnumberNoAnimation duration, in ms.
curveCurve | ICurve | stringNoAnimation curve.

MaxSelected

Represents the maximum number of media assets that can be selected at a time.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
dataMap<MaxCountType, number>NoMaximum number of media assets (images, videos, or both) that can be selected at a time.

SingleLineConfig

Represents the single-line display mode. In single-line mode, the component does not provide functions for viewing a larger image. The component does not support callbacks related to large images, and the PickerController does not support APIs related to large images, making API calls ineffective.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
itemDisplayRatioItemDisplayRatioNoAspect ratio for grid display. Both 1:1 and the original image aspect ratio are supported. The default value is 1:1.
itemBorderRadiusLength | BorderRadiuses | LocalizedBorderRadiusesNoRounded corner radius for grid items.
itemGapLengthNoSpacing between grid items.

DataType

Enumerates the types of data sent from PickerController to the PhotoPickerComponent.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
SET_SELECTED_URIS1Send a list of selected items to instruct the PhotoPickerComponent to refresh the selection status. A string array needs to be passed in.
For example, after an image is deleted from an application's page, the application calls setData() to notify the PhotoPickerComponent of the remaining selected items. Then, the PhotoPickerComponent refreshes the check box status.
SET_ALBUM_URI2Send the selected album to instruct the PhotoPickerComponent to refresh the album data. A string array needs to be passed in.
For example, after an album is selected from an application's page, the application calls setData to notify the PhotoPickerComponent of the URI of the selected album. Then, the PhotoPickerComponent refreshes the album data.

ItemType

Enumerates the types of the item clicked.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
THUMBNAIL0Image or video (thumbnail).
CAMERA1Camera item.

ClickType

Enumerates the click operation types.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
SELECTED0Select (select an image or click a camera item).
DESELECTED1Deselect (deselect an image).

PickerOrientation

Enumerates the sliding preview directions of the Picker grid page. (This capability is not supported currently.)

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
VERTICAL0Vertical direction.
HORIZONTAL1Horizontal direction.

SelectMode

Enumerates the select modes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
SINGLE_SELECT0Select a single option.
MULTI_SELECT1Select multiple options.

PickerColorMode

Enumerates the Picker color modes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
AUTO0Same with the system.
LIGHT1Light mode.
DARK2Dark mode.

ReminderMode

Enumerates the types of the reminder when the number of selected items reaches the maximum.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
NONE0No reminder.
TOAST1Toast message.
MASK2Grayed-out hint.

MaxCountType

Enumerates the types of the maximum count.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
TOTAL_MAX_COUNT0Total number of media assets (images and videos) that can be selected.
PHOTO_MAX_COUNT1Total number of images that can be selected. The value cannot be greater than Total_MAX_Count.
VIDEO_MAX_COUNT2Total number of videos that can be selected. The value cannot be greater than Total_MAX_Count.

PhotoBrowserRange

Enumerates the view range on the photo browser page.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
ALL0View all images and videos.
SELECTED_ONLY1View selected images and videos only.

PhotoBrowserUIElement13+

Represents other UI elements except the image preview component on the photo browser page.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
CHECKBOX0Check box on the photo browser page.
BACK_BUTTON1Back button on the photo browser page.

SaveMode15+

Enumerates the modes for saving images or videos.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
SAVE_AS0Saves the image or video as a new one.
OVERWRITE1Replaces the original image or video. After the replacements, you can roll back the saved content in Gallery to restore the original image or video.

VideoPlayerState14+

Enumerates the video playback states.

Atomic service API: This API can be used in atomic services since API version 14.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
PLAYING0The video is being played.
PAUSED1Video playback is paused.
STOPPED2Video playback is stopped.
SEEK_START3Started dragging the progress bar.
SEEK_FINSH4Finished dragging the progress bar.

ItemDisplayRatio20+

Enumerates the aspect ratios for grid display in single-line display mode.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
SQUARE_RATIO01:1 ratio.
ORIGINAL_SIZE_RATIO1Original image aspect ratio.

Example

// xxx.ets
import {
  PhotoPickerComponent,
  PickerController,
  PickerOptions,
  DataType,
  BaseItemInfo,
  ItemInfo,
  PhotoBrowserInfo,
  AnimatorParams,
  MaxSelected,
  ItemType,
  ClickType,
  PickerOrientation,
  SelectMode,
  PickerColorMode,
  ReminderMode,
  MaxCountType,
  PhotoBrowserRange,
  PhotoBrowserUIElement,
  ItemsDeletedCallback,
  ExceedMaxSelectedCallback,
  CurrentAlbumDeletedCallback,
  videoPlayStateChangedCallback,
  VideoPlayerState
} from '@ohos.file.PhotoPickerComponent';
import photoAccessHelper from '@ohos.file.photoAccessHelper';

@Entry
@Component
struct PickerDemo {
  pickerOptions: PickerOptions = new PickerOptions();
  @State pickerController: PickerController = new PickerController();
  @State selectUris: Array<string> = new Array<string>();
  @State currentUri: string = '';
  @State isBrowserShow: boolean = false;
  private selectedItemsDeletedCallback: ItemsDeletedCallback =
    (baseItemInfos: Array<BaseItemInfo>) => this.onSelectedItemsDeleted(baseItemInfos);
  private exceedMaxSelectedCallback: ExceedMaxSelectedCallback =
    (exceedMaxCountType: MaxCountType) => this.onExceedMaxSelected(exceedMaxCountType);
  private currentAlbumDeletedCallback: CurrentAlbumDeletedCallback = () => this.onCurrentAlbumDeleted();
  private videoPlayStateChangedCallback: videoPlayStateChangedCallback =
    (state: VideoPlayerState) => this.videoPlayStateChanged(state);

  aboutToAppear() {
    this.pickerOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
    this.pickerOptions.maxSelectNumber = 5;
    this.pickerOptions.isSearchSupported = false;
    this.pickerOptions.isPhotoTakingSupported = false;
    this.pickerOptions.photoBrowserCheckboxPosition = [0.5, 0.5];
    // Other attributes
  }

  private onSelect(uri: string): void {
    // Add
    if (uri) {
      this.selectUris.push(uri);
    }
  }

  private onDeselect(uri: string): void {
    // Remove
    if (uri) {
      this.selectUris = this.selectUris.filter((item: string) => {
        return item != uri;
      })
    }
  }

  private onItemClicked(itemInfo: ItemInfo, clickType: ClickType): boolean {
    if (!itemInfo) {
      return false;
    }
    let type: ItemType|undefined = itemInfo.itemType;
    let uri: string|undefined = itemInfo.uri;
    if (type === ItemType.CAMERA) {
      // Click a camera item.
      return true; // If true is returned, the system camera is started. If false is returned, the app processes its services.
    } else {
      if (clickType === ClickType.SELECTED) {
        // The application processes its services.
        if (uri) {
          this.selectUris.push(uri);
          this.pickerOptions.preselectedUris = [...this.selectUris];
        }
        return true; // If true is returned, the check box is selected. Otherwise, the check box is not selected.
      } else {
        if (uri) {
          this.selectUris = this.selectUris.filter((item: string) => {
            return item != uri;
          });
          this.pickerOptions.preselectedUris = [...this.selectUris];
        }
      }
      return true;
    }
  }

  private onEnterPhotoBrowser(photoBrowserInfo: PhotoBrowserInfo): boolean {
    // Callback to be invoked when the photo browser page is displayed.
    this.isBrowserShow = true;
    return true;
  }

  private onExitPhotoBrowser(photoBrowserInfo: PhotoBrowserInfo): boolean {
    // Callback to be invoked when the photo browser page is closed.
    this.isBrowserShow = false;
    return true;
  }

  private onPickerControllerReady(): void {
    // After the callback is called, pickerController APIs can be called to send data to Picker. Before the callback is called, pickerController APIs do not take effect.
    let elements: number[] = [PhotoBrowserUIElement.BACK_BUTTON];
    this.pickerController.setPhotoBrowserUIElementVisibility(elements, false); // Hide the Back button on the photo browser page.
  }

  private onPhotoBrowserChanged(browserItemInfo: BaseItemInfo): boolean {
    // Callback to be invoked when the photo browser is swiped left or right.
    this.currentUri = browserItemInfo.uri ?? '';
    return true;
  }

  private onSelectedItemsDeleted(baseItemInfos: Array<BaseItemInfo>): void {
    // Callback to be invoked when the selected image is deleted.
  }

  private onExceedMaxSelected(exceedMaxCountType: MaxCountType): void {
    // Callback to be invoked when the number of selected items exceeds the maximum.
  }

  private onCurrentAlbumDeleted(): void {
    // Callback to be invoked when the current album is deleted.
  }

  private videoPlayStateChanged(state: VideoPlayerState): void {
    // Called when the video playback state changes.
  }
  build() {
    Flex({
      direction: FlexDirection.Column,
      justifyContent: FlexAlign.Center,
      alignItems: ItemAlign.Center
    }) {
      Column() {
        if (this.isBrowserShow) {
          // Back button of the application on the photo browser page.
          Row() {
            Button("Exit photo browser page").width('33%').height('8%').onClick(() => {
              this.pickerController.exitPhotoBrowser();
            })
          }.margin({ bottom: 20 })
        }

        PhotoPickerComponent({
          pickerOptions: this.pickerOptions,
          // onSelect: (uri: string): void => this.onSelect(uri),
          // onDeselect: (uri: string): void => this.onDeselect(uri),
          onItemClicked: (itemInfo: ItemInfo, clickType: ClickType): boolean => this.onItemClicked(itemInfo,
            clickType), // This API can replace the preceding two APIs.
          onEnterPhotoBrowser: (photoBrowserInfo: PhotoBrowserInfo): boolean => this.onEnterPhotoBrowser(photoBrowserInfo),
          onExitPhotoBrowser: (photoBrowserInfo: PhotoBrowserInfo): boolean => this.onExitPhotoBrowser(photoBrowserInfo),
          onPickerControllerReady: (): void => this.onPickerControllerReady(),
          onPhotoBrowserChanged: (browserItemInfo: BaseItemInfo): boolean => this.onPhotoBrowserChanged(browserItemInfo),
          onSelectedItemsDeleted: this.selectedItemsDeletedCallback,
          onExceedMaxSelected: this.exceedMaxSelectedCallback,
          onCurrentAlbumDeleted: this.currentAlbumDeletedCallback,
          onVideoPlayStateChanged: this.videoPlayStateChangedCallback,
          pickerController: this.pickerController,
        }).height('60%').width('100%')

        // Simulate the selection bar at the bottom of the application.
        if (this.isBrowserShow) {
          Row() {
            ForEach(this.selectUris, (uri: string) => {
              if (uri === this.currentUri) {
                Image(uri)
                  .height('10%')
                  .width('10%')
                  .onClick(() => {
                  })
                  .borderWidth(1)
                  .borderColor('red')
              } else {
                Image(uri).height('10%').width('10%').onClick(() => {
                  this.pickerController.setData(DataType.SET_SELECTED_URIS, this.selectUris);
                  this.pickerController.setPhotoBrowserItem(uri, PhotoBrowserRange.ALL);
                })
              }
            }, (uri: string) => JSON.stringify(uri))
          }
        } else {
          Button('Preview').width('33%').height('5%').onClick(() => {
            if (this.selectUris.length > 0) {
              this.pickerController.setPhotoBrowserItem(this.selectUris[0], PhotoBrowserRange.SELECTED_ONLY);
            }
          })
        }
      }
    }
  }
}

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Media Library Kit (Media File Management Service)

harmony 鸿蒙media_access_helper_capi.h

harmony 鸿蒙media_asset_base_capi.h

harmony 鸿蒙media_asset_capi.h

harmony 鸿蒙media_asset_change_request_capi.h

harmony 鸿蒙media_asset_manager_capi.h

harmony 鸿蒙MediaAssetManager

harmony 鸿蒙MediaLibrary_RequestId

harmony 鸿蒙MediaLibrary_RequestOptions

harmony 鸿蒙moving_photo_capi.h

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/5xG2mR