【问题标题】:Qt rotated image -> polygonQt 旋转图像 -> 多边形
【发布时间】:2016-08-28 17:52:16
【问题描述】:

我有一个QImage,中心在 (x,y),大小 (w,h)。我应用旋转并最终使用QTransform 进行缩放。现在对我来说很容易将新图像(旋转/缩放)放在 (x,y) 的中心。

QTransform transform = QTransform().translate(0,0).rotateRadians(r).scale(s,s);
QImage image = new QImage(old_image->transformed(transform);

我想要一个QPolygon,在旋转/缩放图像的角落有 4 个点。我所有的尝试都失败了。

QPolygon p = QPolygon(QRect(x-w/2, y-h/2, w, h));
QPolygon p2 = transform.map(p);

或

QPolygon p2 = transform.mapToPolygon(QRect(x-w/2, y-h/2, w, h));

我得到的只是一个位置错误的多边形。哪个必须是正确的代码?

【问题讨论】:

    标签: c++ qt qimage qpolygon


    【解决方案1】:

    与图像相反,当我们想要围绕其中心旋转多边形(在本例中为矩形)时,我们必须使用类似的变换

    T = translate(center).rotate(r).translate(-center)
    

    (记住转换是从右到左应用的)。缩放暂时被丢弃。对于图像,这种初始翻译是隐式的。

    这种情况下的问题是图像在旋转后改变了它的尺寸:新图像的大小是包含旋转像素的边界矩形,因此最后的平移不再有效你的情况(translate(center))。

    相反,您需要类似:

    T = translate(new_rect.size() / 2).rotate(r).translate(-original_center)
    

    要实现这一点,您必须将转换分成两部分(缩放也带回来):

    T1 = rotate(r).scale(s, s).translate(-center)
    T2 = translate(new_rect.size() / 2)
    

    因为新的矩形大小只能在应用第一次转换后计算。

    另外,请注意T2 我不是在谈论中心,而是在 半尺寸,因为新中心对于图像的含义与对多边形的含义不同(图像不' t 具有负像素坐标,例如)

    使用 Qt API 表达:

    // Image transformation
    auto transform = QTransform().rotateRadians(r).scale(s, s);
    auto image = m_image.transformed(transform, Qt::SmoothTransformation);
    
    // Assuming something like: QPainter painter(this);
    painter.drawImage(0, 0, image);
    
    // Rect to polygon
    const auto rect = m_image.rect();
    QPolygonF pol;
    pol << rect.topLeft();
    pol << rect.topRight();
    pol << rect.bottomRight();
    pol << rect.bottomLeft();
    
    // First transformation
    const auto center = rect.center();
    transform = transform.translate(-center.x(), -center.y());
    const auto pol2 = transform.map(pol);
    
    // Second transformation
    const auto rect2 = pol2.boundingRect();
    painter.drawPolygon(QTransform().translate(rect2.width() / 2, rect2.height() / 2).map(pol2));
    

    GitHub 中提供完整代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 2013-03-21
      相关资源
      最近更新 更多