QPixmap将绘制的正方形的内容复制到另一个图像中

QPixmap copy contents of a square drawn into another image

本文关键字:另一个 图像 复制 绘制 正方形 QPixmap      更新时间:2023-10-16

我有一个图像,我在上面画了一个矩形。之后,我尝试将矩形的内容复制到另一个 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);

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

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

逻辑中的问题是目标图像和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);
[..]