九宫格裁剪解决的是朋友圈发图的经典需求:把一张长图切成 9 张正方形,且每块要像素级对齐。
形态和自由裁剪正好相反——框固定、图片动,而且只能上下移动,横向由九宫格线自己切。
难点集中在三处:movable-view 与 movable-area 的坐标系换算、9 张图共用一块画布的绘制时序、以及安卓上 dpr 过高导致导出直接失败。
下面按「布局数学 → 移动夹取 → 串行导出 → dpr」的顺序拆。
背景
文件在 pages/img/nineSquareGridClip.tsx,canvas 工具复用 utils/canvas.tsx,九宫格线用 4 条 View 画。
页面只有一个正方形裁剪区,边长取屏幕宽 windowWidth,垂直居中:
1 2 3 4 5 6 7
| const { windowWidth, windowHeight } = getWindowInfo() const top = (windowHeight - windowWidth) / 2 const gap = (windowWidth - 4) / 3
const [clipPoints, setclipPoints] = useState({ top, gap }) const [init, setInit] = useState({ y: 0, bottomLine: top, movey: -top })
|
三个量要区分清楚:
| 量 |
含义 |
gap |
单格边长(显示 px),也是每张切图在显示坐标系下的边长 |
clipPoints.top |
正方形裁剪区距屏幕顶部的距离 |
init.bottomLine |
图片相对裁剪框上移的量,等于 -init.movey |
实现
1. 布局数学:为什么 movable-view 的 top 要取负值
源码注释本身就是一份说明书,值得完整保留:
翻译成人话:裁剪区是个正方形(边长 = 屏宽),而图片通常比它高。想让图片在正方形框里上下滑动,就得让 MovableView 比 MovableArea 大;直接设会卡在边界,所以把 MovableView 的 top 设成负值,让它的坐标系整体上移,等价于「初始时正方形框正好对准图片的中上部」。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <MovableArea className="w-screen z-20 border-2 box-border" style={{ height: `${imgInfo.imgCurWidth}px` }} > <MovableView direction="vertical" /* 只允许竖直移动 */ className="w-screen" style={{ height: `${imgInfo.imgCurHeight - init.bottomLine}px`, top: `-${init.bottomLine}px`, }} onTouchStart={(e) => handleImgStart(e)} onTouchMove={(e) => handleImgMove(e)} > <Image src={imgUrlState} mode="widthFix" className={`w-screen ${isClip ? 'opacity-50' : ''}`} /> </MovableView> </MovableArea>
|
九宫格线用 4 条 View 画(2 横 2 竖),都压在 z-30:
1 2 3 4
| <View className="absolute bg-black z-30 w-screen" style={{ height: '2px', top: `${clipPoints.gap}px` }} /> <View className="absolute bg-black z-30 w-screen" style={{ height: '2px', bottom: `${clipPoints.gap}px` }} /> <View className="absolute bg-black z-30" style={{ width: '2px', height: `${imgInfo.imgCurWidth}px`, right: `${clipPoints.gap}px` }} /> <View className="absolute bg-black z-30" style={{ width: '2px', height: `${imgInfo.imgCurWidth}px`, left: `${clipPoints.gap}px` }} />
|
2. 移动夹取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const handleImgMove = (e) => { const { imgCurWidth, imgCurHeight } = imgInfo const { clientY } = e.touches[0] const moveDistance = clientY - init.y const newMovey = init.movey + moveDistance
const maxMoveUp = -Math.max(0, imgCurHeight - imgCurWidth) const maxMoveDown = 0 const clamped = Math.max(maxMoveUp, Math.min(maxMoveDown, newMovey))
setInit((prev) => ({ ...prev, y: clientY, movey: clamped, bottomLine: -clamped, })) }
|
『bottomLine 与 movey 互为相反数』——下面切图用的就是 init.bottomLine,保证「屏幕看到的位置」和「canvas 取源的位置」是同一套坐标。
3. 一次生成 9 张(串行 + rAF)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| const onFinish = async () => { showLoading({ title: '正在裁剪图片', mask: true })
const { gap } = clipPoints const { scale } = imgInfo const clipGap = gap / scale
const { ctx, canvas } = await getCanvasCtx('canvas', clipGap, clipGap) const img = canvas.createImage()
await new Promise((resolve, reject) => { img.src = imgUrlState img.onload = resolve img.onerror = reject })
const tempFilePaths: string[] = [] for (let index = 0; index < 9; index++) { ctx.clearRect(0, 0, clipGap, clipGap)
ctx.drawImage( img, (gap * (index % 3)) / scale, (init.bottomLine + gap * Math.floor(index / 3)) / scale, clipGap, clipGap, 0, 0, clipGap, clipGap )
const tempFilePath = await new Promise<string>((resolve) => { requestAnimationFrame(async () => { try { const result = await canvasToTempFilePath({ canvas, x: 0, y: 0, destWidth: canvas.width, destHeight: canvas.height, fileType: 'png', }) resolve(result.tempFilePath) } catch (error) { console.error('获取临时文件失败:', error) resolve('') } }) })
if (tempFilePath) tempFilePaths.push(tempFilePath) }
canvasRef.current = canvas setImgUrls(tempFilePaths) setIsClip(false) hideLoading() }
|
索引换算:index % 3 是列号,Math.floor(index / 3) 是行号,所以第 i 块的源坐标是 (gap * 列, bottomLine + gap * 行),再整体 ÷ scale 换回原图像素。
4. 逐张保存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const saveImg = (num: number) => { if (num > imgUrls.length - 1) { hideLoading() offClip() return }
showLoading({ title: '正在保存图片', mask: true }) saveImageToPhotosAlbum({ filePath: imgUrls[num], success: () => saveImg(num + 1), fail: () => { hideLoading() showToast({ title: '保存失败,请检查相册权限', icon: 'none' }) }, }) }
|
递归而不是 Promise.all:相册保存 API 串行更稳,中途失败能立刻停下,不会出现「只存了一半还继续跑」。
5. dpr 兼容
utils/canvas.tsx 里的处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| export const getCanvasCtx = async (selectorID = '', width: number, height: number) => { return new Promise((resolve, reject) => { createSelectorQuery() .select(`#${selectorID}`) .fields({ node: true, size: true }) .exec((res) => { if (!res[0]) { reject({ msg: '获取 canvas 失败' }) return } const canvas = res[0].node const ctx = canvas.getContext('2d') const { pixelRatio } = getWindowInfo() const dpr = pixelRatio >= 3 ? 1 : pixelRatio
canvas.width = width * dpr canvas.height = height * dpr ctx.scale(dpr, dpr) resolve({ ctx, canvas }) }) }) }
|
为什么压到 1:九宫格每块边长 ≈ 屏宽 / 3,若 dpr = 3,canvas.width ≈ width * 3,再连着导出 9 张,安卓的 native buffer 直接超限。压成 1 后分辨率略降,但稳定可用。
踩坑
canvas.width / height 必须显式设:不设的话 canvas 默认 300×150,绘制内容会被拉伸。注释里写的「只有给 canvas 设置宽高,绘制出来的 canvas 大小才会一致」就是这个意思。
- **每次绘制前
clearRect**:9 张图共用一块画布,不清就会叠影。
- 导出要等一帧:
drawImage 是同步的,但 canvasToTempFilePath 读的是 native 缓冲,必须 requestAnimationFrame(或 setTimeout)之后再读。rAF 比 setTimeout(…, 100) 更准,因为它对齐的是绘制帧。
- 移动边界要用「带符号的差值」:
Math.max(0, 图高 - 框高) 再取负,比直接 图宽 - 图高 安全,图比框矮时不会把下界翻成正数。
- **越界判断一定要
return**:递归 + 数组下标是最容易漏 return 的组合,undefined 会一路传到 API 层才报错。
- 预览层用
imgUrls.length === 9 当开关:不用额外的 isDone 状态,数据本身就表达了完成度。
- 卸载时清理:
useEffect 的 cleanup 里 clearRect + setImgUrls([]),释放画布与临时文件引用。
- 可扩展:注释里留了「后期加缩放」的待办,也就是给
MovableView 加 scale 能力;加了之后 gap 与 clipGap 的换算要同步带上缩放系数,否则切图会错位。