7.0.3-0.2.1 • Published 8 months ago

@ohmi/react-native-image-picker v7.0.3-0.2.1

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months ago

模板版本:v0.3.0

本项目基于 react-native-image-picker@1.1.0 开发。

1. 安装与使用

进入到工程目录并输入以下命令:

npm

npm install @ohmi/react-native-image-picker

yarn

yarn add @ohmi/react-native-image-picker

下面的代码展示了这个库的基本使用场景:

import React from 'react';
import { View, Text } from 'react-native';
import ImagePicker from 'react-native-image-picker';

const App = () => {
  const [urlInfo, setUrlInfo] = React.useState<string>();
  return (
    <View style={{ flex: 1, marginTop: 100 }}>
      <View style={{
        width: 160,
        height: 36,
        backgroundColor: 'hsl(190,50%,70%)',
        paddingHorizontal: 16,
        paddingVertical: 8,
        borderRadius: 8
      }} onTouchEnd={() => {
        ImagePicker.launchImageLibrary({ mediaType: 'photo', selectionLimit: 1 }, (data) => {
          if (data.assets?.length) {
            setUrlInfo(JSON.stringify(data.assets))
          }
        })
      }}>
        <Text style={{ width: '100%', height: '100%', fontWeight: 'bold', textAlign: 'center' }}>选择</Text>
      </View>
      <Text>{urlInfo}</Text>
    </View>
  );
};

export default App;

2. Manual Link

此步骤为手动配置原生依赖项的指导。

首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony

2.1. Overrides RN SDK

为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。

关于该字段的作用请阅读官方说明

{
  "overrides": {
    "@rnoh/react-native-openharmony": "^0.72.38" // ohpm 在线版本
    // "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // 指向本地 har 包的路径
    // "@rnoh/react-native-openharmony" : "./react_native_openharmony" // 指向源码路径
  }
}

2.2. 引入原生端代码

目前有两种方法:

  • 通过 har 包引入;
  • 直接链接源码。

方法一:通过 har 包引入(推荐)

!TIP har 包位于三方库安装路径的 harmony 文件夹下。

打开 entry/oh-package.json5,添加以下依赖

"dependencies": {
    "@ohmi/react-native-image-picker": "file:../../node_modules/@ohmi/react-native-image-picker/harmony/image_picker.har",
  }

点击右上角的 sync 按钮

或者在终端执行:

cd entry
ohpm install

方法二:直接链接源码

!TIP 如需使用直接链接源码,请参考直接链接源码说明

2.3. 配置 CMakeLists 和引入 RNImagePickerPackage

打开 entry/src/main/cpp/CMakeLists.txt,添加:

project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)

add_subdirectory("${RNOH_CPP_DIR}" ./rn)

# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@ohmi/react-native-image-picker/src/main/cpp" ./image_picker)
# RNOH_END: manual_package_linking_1

file(GLOB GENERATED_CPP_FILES "./generated/*.cpp")

add_library(rnoh_app SHARED
    ${GENERATED_CPP_FILES}
    "./PackageProvider.cpp"
    "${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)

# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_image_picker)
# RNOH_END: manual_package_linking_2

打开 entry/src/main/cpp/PackageProvider.cpp,添加:

#include "RNOH/PackageProvider.h"
#include "generated/RNOHGeneratedPackage.h"
#include "SamplePackage.h"
+ #include "RNImagePickerPackage.h"

using namespace rnoh;

std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
    return {
        std::make_shared<RNOHGeneratedPackage>(ctx),
        std::make_shared<SamplePackage>(ctx),
+       std::make_shared<RNImagePickerPackage>(ctx),
    };
}

2.4. 在 ArkTs 侧引入 RNImagePickerPackage

打开 entry/src/main/ets/RNPackagesFactory.ts,添加:

import type {RNPackageContext, RNPackage} from 'rnoh/ts';
import {SamplePackage} from 'rnoh-sample-package/ts';
+ import { RNImagePickerPackage } from '@ohmi/react-native-image-picker/ts';

export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
  return [
    new SamplePackage(ctx),
+   new RNImagePickerPackage(ctx)
  ];
}

2.5. 添加相机权限

打开 entry/src/main/module.json5,添加:

{
  "module": {
    ...
    "requestPermissions": [
    ...
      {
        "name": "ohos.permission.CAMERA",
        "reason": "$string:CAMERA",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      },
    ]
  }
}

2.6. 运行

点击右上角的 sync 按钮

或者在终端执行:

cd entry
ohpm install

然后编译、运行即可。

3. 约束与限制

3.1. 兼容性

要使用此库,需要使用正确的 React-Native 和 RNOH 版本。另外,还需要使用配套的 DevEco Studio 和 手机 ROM。

请到三方库相应的 Releases 发布地址查看 Release 配套的版本信息:@ohmi/react-native-image-picker Releases

4. API

!TIP "Platform"列表示该属性在原三方库上支持的平台。

!TIP "HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。

NameDescriptionTypeRequiredPlatformHarmonyOS Support
showImagePickerBoth launchCamera and launchImageLibrary.functionyesiOS Androidyes
launchCameraLaunch camera to take photo or video.functionyesiOS Androidyes
launchImageLibraryLaunch gallery to pick image or video.functionyesiOS Androidyes

属性

!TIP "Platform"列表示该属性在原三方库上支持的平台。

!TIP "HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。

ImagePickerOptions

NameDescriptionTypeRequiredPlatformHarmonyOS Support
titleSpecify null or empty string to remove the titlestringnoiOS Androidyes
cancelButtonTitleSpecify null or empty string to remove this buttonstringnoiOS Androidyes
takePhotoButtonTitleSpecify null or empty string to remove this buttonstringnoiOS Androidyes
chooseFromLibraryButtonTitleSpecify null or empty string to remove this buttonstringnoiOS Androidyes
chooseWhichLibraryTitleSpecify null or empty string to use default Android title. Is shown when user has multiple apps that can open library.stringnoAndroidno
customButtonsAn array containing objects with the name and title of buttonsImagePickerCustomButtonOptions[]noiOS Androidyes
cameraType'front' or 'back''front' | 'back'noiOSyes
mediaType'photo', 'video', or 'mixed' on iOS, 'photo' or 'video' on Android'photo' | 'video' | 'mixed'yesiOS Androidyes
maxWidthPhotos onlynumbernoiOS Androidyes
maxHeightPhotos onlynumbernoiOS Androidyes
quality0 to 1, photos onlynumbernoiOS Androidno
videoQuality'low', 'medium', or 'high' on iOS, 'low' or 'high' on Android'low' | 'medium' | 'high'noiOS Androidno
durationLimitMax video recording time, in secondsnumbernoiOS Androidno
rotationPhotos only, 0 to 360 degrees of rotationnumbernoAndroidno
allowsEditingbool - enables built-in iOS functionality to resize the image after selectionbooleannoiOSyes
noDataIf true, disables the base64 data field from being generated (greatly improves performance on large photos)booleannoiOS Androidyes
storageOptionsIf this key is provided, the image will be saved in your app's Documents directory on iOS, or your app's Pictures directory on Android (rather than a temporary directory)ImagePickerStorageOptionsnoiOS Androidpartially
permissionDeniedOptions when the permission is deniedImagePickerPermissionDeniedOptionsnoAndroidyes
tintColorApplication color schemestringnoiOSno

launchCamera Options

NameDescriptionTypeRequiredPlatformHarmonyOS Support
cameraType'front' or 'back''front' | 'back'noiOSyes
mediaType'photo', 'video', or 'mixed' on iOS, 'photo' or 'video' on Android'photo' | 'video' | 'mixed'yesiOS Androidyes
maxWidthPhotos onlynumbernoiOS Androidyes
maxHeightPhotos onlynumbernoiOS Androidyes
quality0 to 1, photos onlynumbernoiOS Androidno
videoQuality'low', 'medium', or 'high' on iOS, 'low' or 'high' on Android'low' | 'medium' | 'high'noiOS Androidno
durationLimitMax video recording time, in secondsnumbernoiOS Androidno
rotationPhotos only, 0 to 360 degrees of rotationnumbernoAndroidno
noDataIf true, disables the base64 data field from being generated (greatly improves performance on large photos)booleannoiOS Androidyes
storageOptionsIf this key is provided, the image will be saved in your app's Documents directory on iOS, or your app's Pictures directory on Android (rather than a temporary directory)ImagePickerStorageOptionsnoiOS Androidpartially
permissionDeniedOptions when the permission is deniedImagePickerPermissionDeniedOptionsnoAndroidyes

launchImageLibrary Options

NameDescriptionTypeRequiredPlatformHarmonyOS Support
mediaType'photo', 'video', or 'mixed' on iOS, 'photo' or 'video' on Android'photo' | 'video' | 'mixed'yesiOS Androidyes
maxWidthPhotos onlynumbernoiOS Androidyes
maxHeightPhotos onlynumbernoiOS Androidyes
quality0 to 1, photos onlynumbernoiOS Androidno
videoQuality'low', 'medium', or 'high' on iOS, 'low' or 'high' on Android'low' | 'medium' | 'high'noiOS Androidno
rotationPhotos only, 0 to 360 degrees of rotationnumbernoAndroidno
allowsEditingbool - enables built-in iOS functionality to resize the image after selectionbooleannoiOSyes
noDataIf true, disables the base64 data field from being generated (greatly improves performance on large photos)booleannoiOS Androidyes
permissionDeniedOptions when the permission is deniedImagePickerPermissionDeniedOptionsnoAndroidyes
tintColorApplication color schemestringnoiOSno

ImagePickerCustomButtonOptions

NameDescriptionTypeRequiredPlatformHarmonyOS Support
nameCustom button namestringnoiOS Androidyes
titleCustom button titlestringnoiOS Androidyes

ImagePickerStorageOptions

NameDescriptionTypeRequiredPlatformHarmonyOS Support
skipBackupIf true, the photo will NOT be backed up to iCloudbooleannoiOSno
pathIf set, will save the image at Documents/[path]/ rather than the root Documents for iOS, and Pictures/[path]/ on Android.stringnoiOS Androidyes
cameraRollIf true, the cropped photo will be saved to the iOS Camera Roll or Android DCIM folder.booleannoiOS Androidno
waitUntilSavedIf true, will delay the response callback until after the photo/video was saved to the Camera Roll. If the photo or video was just taken, then the file name and timestamp fields are only provided in the response object when this AND cameraRoll are both true.booleannoiOSno

ImagePickerPermissionDeniedOptions

NameDescriptionTypeRequiredPlatformHarmonyOS Support
titleTitle of explaining permissions dialog. By default Permission denied.stringnoAndroidyes
textMessage of explaining permissions dialog. By default To be able to take pictures with your camera and choose images from your library..stringnoAndroidyes
reTryTitleTitle of re-try button. By default re-trystringnoAndroidyes
okTitleTitle of ok button. By default I'm surestringnoAndroidyes

ImagePickerResponse

NameDescriptionTypeRequiredPlatformHarmonyOS Support
didCancelInforms you if the user cancelled the processbooleannoiOS Androidyes
errorContains an error message, if there is onestringnoiOS Androidyes
customButtonIf the user tapped one of your custom buttons, contains the name of itstringnoiOS Androidyes
dataThe base64 encoded image data (photos only)stringnoiOS Androidyes
uriThe uri to the local file asset on the device (photo or video)stringnoiOS Androidyes
origURLThe URL of the original asset in photo library, if it existsstringnoiOSyes
isVerticalWill be true if the image is vertically orientedbooleannoiOS Androidyes
widthImage dimensions (photos only)numbernoiOS Androidyes
heightImage dimensions (photos only)numbernoiOS Androidyes
fileSizeThe file size (photos only)numbernoiOS Androidyes
typeThe file type (photos only)stringnoiOS Androidyes
fileNameThe file name, if availablestringnoiOS Androidyes
pathThe file pathstringnoiOS Androidyes
latitudeLatitude metadata, if availablenumbernoiOS Androidno
longitudeLongitude metadata, if availablenumbernoiOS Androidno
timestampTimestamp metadata, if available, in ISO8601 UTC formatstringnoiOS Androidyes
originalRotationRotation degrees (photos only)numbernoAndroidyes

5. 遗留问题

  • react-native-image-picker 部分属性和返回值未适配 HarmonyOS

6. 其他

7. 开源协议

本项目基于 The MIT License (MIT) ,请自由地享受和参与开源。