如何在react-native-image-crop-picker裁剪图片时设置最小及最大宽高比
解决方案
方案1:无侵入裁剪后校验(推荐,无需修改依赖源码)
react-native-image-crop-picker 本身没有提供裁剪阶段实时限制宽高比范围的配置项,该方案实现成本最低、上线无风险,仅需在拿到裁剪结果后做规则校验,不符合要求则提示用户重新裁剪即可。
首先新增公共校验函数,完全匹配你的需求规则:
// 裁剪结果校验函数 const validateCropResult = (cropRect) => { const { width, height } = cropRect const aspectRatio = width / height // 自定义规则 const minRatio = 1/3 const maxRatio = 1.4 const minWidth = 200 const maxHeight = 1000 if (width < minWidth) { return { pass: false, msg: `裁剪宽度不能小于${minWidth}px,请重新调整` } } if (height > maxHeight) { return { pass: false, msg: `裁剪高度不能大于${maxHeight}px,请重新调整` } } if (aspectRatio < minRatio || aspectRatio > maxRatio) { return { pass: false, msg: `裁剪宽高比需在${minRatio.toFixed(2)}~${maxRatio.toFixed(1)}之间,请重新调整` } } return { pass: true } }
之后修改你的拍照、选图逻辑,注意先删掉openPicker配置中多余的ra字符,同时调大compressImageMaxWidth避免压缩后无法满足最小宽度要求:
import { Alert } from 'react-native' const takePhotoFromCamera = () => { ImagePicker.openCamera({ compressImageMaxWidth: 2000, compressImageMaxHeight: 1000, cropping: true, freeStyleCropEnabled: true, }).then((image) => { const { cropRect } = image; // 优先校验裁剪结果 const validateRes = validateCropResult(cropRect) if (!validateRes.pass) { Alert.alert('提示', validateRes.msg) return } // 校验通过后执行后续逻辑 const imageUri = Platform.OS === 'ios' ? image.sourceURL : image.path; const ImgDimensions = {width: cropRect.width, height: cropRect.height}; setImage(imageUri); setImgDims(ImgDimensions); }).catch(err => { // 处理用户主动取消等异常场景 console.log('操作取消:', err) }); }; const choosePhotoFromLibrary = () => { ImagePicker.openPicker({ compressImageMaxWidth: 2000, compressImageMaxHeight: 1000, cropping: true, freeStyleCropEnabled: true, compressImageQuality: 0.8, }).then((image) => { const { cropRect } = image; // 优先校验裁剪结果 const validateRes = validateCropResult(cropRect) if (!validateRes.pass) { Alert.alert('提示', validateRes.msg) return } // 校验通过后执行后续逻辑 const imageUri = Platform.OS === 'ios' ? image.sourceURL : image.path; const ImgDimensions = {width: cropRect.width, height: cropRect.height}; setImage(imageUri); setImgDims(ImgDimensions); }).catch(err => { console.log('操作取消:', err) }); };
方案2:原生修改实现实时裁剪限制
如果产品要求裁剪阶段就无法拉出不符合规则的裁剪框,可以修改依赖的原生源码实现:
- iOS 端修改 TOCropViewController 配置,设置
aspectRatioLockEnabled为true,同时传入自定义的宽高比范围 - 安卓端修改 uCrop 配置,调用
setAspectRatioBounds方法传入最小、最大宽高比即可
该方案后续升级react-native-image-crop-picker版本时会出现冲突,需要重新适配,非强需求不推荐使用。
内容的提问来源于stack exchange,提问作者SONKENG MBOGNING Brice D. N.
相关产品推荐
相关产品推荐

