banner
banner
banner
NEWS LETTER

Taro 九宫格裁剪:movable 数学与 dpr 兼容

Scroll down

九宫格裁剪解决的是朋友圈发图的经典需求:把一张长图切成 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 // 单格边长,4 = 两条 2px 分隔线

// 直接作为 useState 的初始值,别在渲染期间调 setState
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 要取负值

源码注释本身就是一份说明书,值得完整保留:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* movable-area 和 movable-view 的注意事项:
* tip1: 当 movable-view 小于 movable-area 时,movable-view 的移动范围是在 movable-area 内;
* tip2: 当 movable-view 大于 movable-area 时,movable-view 的移动范围必须包含 movable-area(x / y 轴分开考虑)
*
* 如何让图片最底部拉上去时刚好图片底部与 movableArea 底部接触?
* 1. 因为 movableArea 与 movableView 的 top 值是相同的,所以 movableView 的内容是相对 movableArea 的 top 值来计算的
* 2. movable-view 的高度 = 小程序显示的图片高度 - 图片移动的高度 - movableArea 的 top 值
* 3. 如果给 movableView 的 top 添加一个负值,movableView 就可以上下移动,并且公式变成:
* movable-view 的高度 = 小程序显示的图片高度 - 图片移动的高度
*
* 原因:刚开始 movable-view 会大于 movable-area(触发 tip2),随着移动 movable-view 小于 movable-area(触发 tip1)
*/

翻译成人话:裁剪区是个正方形(边长 = 屏宽),而图片通常比它高。想让图片在正方形框里上下滑动,就得让 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

// 只有「图比框高」时才存在向上空间,差值先夹到 0 以上再取负
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, // 与 movey 保持同步关系
}))
}

『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 // 显示尺寸 → 原图像素,dpr 交给 getCanvasCtx

const { ctx, canvas } = await getCanvasCtx('canvas', clipGap, clipGap)
const img = canvas.createImage()

// 用 Promise 等图片加载完成,别用 setTimeout 赌时间
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) // ★ 9 张共用一块画布,每次先清

// 与渲染使用同一参考值 bottomLine,保证裁剪区域准确
ctx.drawImage(
img,
(gap * (index % 3)) / scale, // sx:第几列
(init.bottomLine + gap * Math.floor(index / 3)) / scale, // sy:第几行
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) // 9 张都拿到后再渲染预览
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) => {
// 越界说明 9 张已经存完,必须先返回
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 兼容

1
2
3
4
5
6
/**
* 安卓手机报 canvas ToTempFilePath: fail: convert native buffer parameter fail,
* native buffer exceeded size limit?
* 原因: dpr 超过 3
* 解决: 在 getCanvasCtx 中把 dpr 压成 1
*/

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 // ★ 唯一一次乘 dpr

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 的换算要同步带上缩放系数,否则切图会错位。
其他文章
目录导航 置顶
  1. 1. 背景
  2. 2. 实现
    1. 2.1. 1. 布局数学:为什么 movable-view 的 top 要取负值
    2. 2.2. 2. 移动夹取
    3. 2.3. 3. 一次生成 9 张(串行 + rAF)
    4. 2.4. 4. 逐张保存
    5. 2.5. 5. dpr 兼容
  3. 3. 踩坑
请输入关键词进行搜索