You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么postRotate()方法会改变X轴方向?镜像贴纸旋转后位置角度异常

问题根因

你的代码出现旋转后镜像异常,核心是三个逻辑错误:

  • 矩阵变换的旋转锚点错误:postRotate默认围绕坐标系左上角(0,0)旋转,并非围绕贴纸自身中心旋转,只要贴纸存在旋转角度,最终的位置就会出现大幅偏移
  • 旋转角度未做镜像适配:水平翻转后,贴纸的旋转方向会反向,比如原始贴纸顺时针旋转30°,镜像后的贴纸应该逆时针旋转30°,也就是角度值取负
  • 镜像坐标参考点错误:你用贴纸左上角的平移值transX计算镜像位置,贴纸旋转后左上角的坐标和整体边界已经发生变化,用贴纸中心点作为镜像参考的计算逻辑更稳定

修复代码

仅需要修改getReflectedMatrix方法即可:

public Matrix getReflectedMatrix(int wrapperWidth, Sticker sticker) {
    Matrix matrix = sticker.getMatrix();
    float transX = getMatrixValue(matrix, 2);
    float transY = getMatrixValue(matrix, 5);
    float currentAngle = sticker.getCurrentAngle();
    float currentScale = sticker.getCurrentScale();
    // 注意:如果getCurrentWidth/getCurrentHeight返回的是原始未缩放尺寸,需要乘以currentScale
    float stickerWidth = sticker.getCurrentWidth();
    float stickerHeight = sticker.getCurrentHeight();

    // 计算原始贴纸的中心点坐标
    float originalCenterX = transX + stickerWidth / 2f;
    float originalCenterY = transY + stickerHeight / 2f;

    // 水平镜像:以容器的左右中线为对称轴,计算镜像后的中心点
    float mirroredCenterX = wrapperWidth - originalCenterX;
    float mirroredCenterY = originalCenterY;
    // 镜像后旋转角度取反,适配翻转后的旋转方向
    float mirroredAngle = -currentAngle;

    Matrix newMatrix = new Matrix();
    // 旋转、缩放都以贴纸自身中心为锚点,避免偏移
    newMatrix.postRotate(mirroredAngle, stickerWidth/2f, stickerHeight/2f);
    newMatrix.postScale(currentScale, currentScale, stickerWidth/2f, stickerHeight/2f);
    // 平移到镜像后的中心点位置,换算回左上角的平移坐标
    newMatrix.postTranslate(mirroredCenterX - stickerWidth/2f, mirroredCenterY - stickerHeight/2f);

    return newMatrix;
}

内容的提问来源于stack exchange,提问作者user7954210

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 16:15:06