以防万一其他人正在寻找解决方案。
我能做到这一点的唯一方法是计算在哪里裁剪原始图像。
const crop = () => {
if (content.width > content.height) {
const [cropX, cropY, cropW, cropH] = cropBasedOnWidth();
if (cropY < 0) {
const [cropX, cropY, cropW, cropH] = cropBasedOnHeight();
return {x: cropX, y: cropY, height: cropH, width: cropW};
}
return {x: cropX, y: cropY, height: cropH, width: cropW};
} else if (content.width < content.height) {
const [cropX, cropY, cropW, cropH] = cropBasedOnHeight();
if (cropX < 0) {
const [cropX, cropY, cropW, cropH] = cropBasedOnWidth();
return {x: cropX, y: cropY, height: cropH, width: cropW};
}
return {x: cropX, y: cropY, height: cropH, width: cropW};
} else {
return undefined;
}
}
const cropBasedOnWidth = () => {
const cropW = content.naturalWidth;
const cropH = cropW / content.width * content.height;
const cropX = content.naturalWidth / 2 - cropW / 2;
const cropY = content.naturalHeight / 2 - cropH / 2;
return [cropX, cropY, cropW, cropH];
}
const cropBasedOnHeight = () => {
const cropH = content.naturalHeight;
const cropW = cropH / content.height * content.width;
const cropX = content.naturalWidth / 2 - cropW / 2;
const cropY = content.naturalHeight / 2 - cropH / 2;
return [cropX, cropY, cropW, cropH];
}
...
return <Image crop={crop()} ... />
不知道有没有更好的办法。