【问题标题】:QPixmap copy contents of a square drawn into another imageQPixmap 将一个正方形的内容复制到另一个图像中
【发布时间】:2014-01-14 03:53:51
【问题描述】:

我有一个图像,我在上面画了一个矩形。之后,我试图将矩形的内容复制到另一个 QLabel 上。这似乎可行,但是我似乎无法从图像的左上角开始对齐复制的图像。这就是我正在做的事情

QPixmap original_image; 
original_image.load("c:\\Images\\myimg.jpg");
original_image = original_image.scaled(ui.label->size().width(),ui.label->size().height());

//-----------------------------------------------------------------------
//Draw rectangle on this
QPixmap target_two(ui.label->size().width(),ui.label->size().height());
target_two.fill(Qt::transparent);     

QPixmap target(ui.label->size().width(),ui.label->size().height());
target.fill(Qt::transparent);    

QPainter painter(&target);
QPainter painter_two(&target_two);


QRegion r(QRect(0, 0, ui.label->size().width(), ui.label->size().height()), QRegion::RegionType::Rectangle);  //Region to start copying
painter.setClipRegion(r);
painter.drawPixmap(0, 0, original_image); //Draw the original image in the clipped region 


QRectF rectangle(x_start,y_start,clipRegion);
painter.drawRoundedRect(rectangle,0,0); //Last two parameters define the radius of the corners higher the radius more rounded it is

             QRegion r_two(rectangle.toRect(), QRegion::RegionType::Rectangle); 
             painter_two.setClipRegion(r_two);
             painter_two.drawPixmap(0,0,target); 


ui.label->setPixmap(target);    

ui.label_2->setPixmap(target_two);

底部图片是带有红色矩形的图像,这很好。 上图是正方形内容的副本。唯一的问题是它不是从左上角开始的。

关于为什么我没有在左上角获得复制内容的任何建议。

【问题讨论】:

    标签: c++ qt qtgui qpainter qpixmap


    【解决方案1】:

    您的逻辑中的问题是 target 和 target_two 图像具有相同的大小 - 标签大小,并且您将复制的图像绘制在与初始标签相同的位置。到现在为止还挺好。我将通过以下代码解决此问题:

    [..]
    // This both lines can be removed.
    // QRegion r_two(rectangle.toRect(), QRegion::RegionType::Rectangle); 
    // painter_two.setClipRegion(r_two);
    
    // Target rect. in the left top corner.
    QRectF targetRect(0, 0, rectangle.width(), rectangle.height());
    QRectF sourceRect(rectangle);
    // Draw only rectangular area of the source image into the new position.
    painter_two.drawPixmap(targetRect, target, sourceRect);
    [..]
    

    【讨论】:

    • 谢谢你完美地完成了这个技巧你能解释一下painter_two.drawPixmap(targetRect, target, sourceRect);发生了什么以及为什么我们创建了一个新的QRectF sourceRect?
    • @MistyD 它将源图像的一部分绘制到目标矩形区域中。创建 sourceRect 是为了使代码更容易理解,但从技术上讲,您可以删除它并简单地使用“矩形”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    相关资源
    最近更新 更多