首页 > 解决方案 > react-native-image-crop-tools CropView 未显示要裁剪的图像

问题描述

我正在使用react-native-image-crop-tools裁剪图像,但 CropView 没有显示要裁剪的图像,只显示了一个空白屏幕。有什么解决方案吗?

import { CropView } from 'react-native-image-crop-tools';

const [uri, setUri] = useState('https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg');

{uri !== undefined && <CropView
sourceUrl={uri}
style={{flex:1}}
ref={cropViewRef}
onImageCrop={(res) => console.warn(res)}
keepAspectRatio
aspectRatio={{ width: 16, height: 9 }}
/>}

标签: react-native

解决方案


该库不支持远程图像。它在 iOS 中的工作只是巧合,就像原生 ios 库支持网络图像的裁剪一样。

如果要裁剪远程图像,请先使用 RNFetchBlob 下载它,然后将本地文件路径传递给它。

直接支持远程图像是一项有点复杂的任务,超出了本项目的范围。

您还可以在图书馆中查看已关闭的问题。

https://github.com/hhunaid/react-native-image-crop-tools/issues/16

您可以尝试使用以下示例在 android 平台中裁剪网络图像:

例如:

import React, {useCallback, useEffect, useState} from 'react';
import {View, Text} from 'react-native';
import {CropView} from 'react-native-image-crop-tools';
import RNFetchBlob from 'rn-fetch-blob';

export default () => {
  const [uri, setUri] = useState('');

  const getImage = useCallback(() => {
    try {
      RNFetchBlob.config({
        fileCache: true,
        // by adding this option, the temp files will have a file extension
        appendExt: 'png',
      })
        .fetch(
          'GET',
          'https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg',
        )
        .then(res => {
          let status = res.info().status;

          if (status === 200) {
            setUri('file://' + res.path());
          } else {
            console.log(status);
          }
        })
        // Something went wrong:
        .catch((errorMessage, statusCode) => {
          // error handling
          console.log('Error : ', errorMessage);
        });
    } catch (err) {
      console.log('Error : ', err.message);
    }
  }, []);

  useEffect(() => {
    getImage();
  }, [getImage]);

  if (uri === '') {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>{'processing...'}</Text>
      </View>
    );
  }

  return (
    <CropView
      sourceUrl={uri}
      style={{flex: 1, height: '100%', width: '100%'}}
      // ref={cropViewRef}
      onImageCrop={res => console.warn(res)}
      keepAspectRatio
      aspectRatio={{width: 16, height: 9}}
    />
  );
};

推荐阅读