가운데 정렬 QPainter
에 이미지를 그리는 방법이 있습니까? 나는 QPainter::drawText
이 우리에게이 조항을 제공한다고보고 있지만 drawImage
은 그렇지 않습니다. 하나의 소스 rect, 대상 rect 및 이미지가 있습니다. 원본 크기가 작 으면 이미지가 페이지의 왼쪽에 그려집니다. 중앙에 정렬하여 인쇄하고 싶습니다.QPainter DrawImage CenterAligned
2
A
답변
2
내가 (소스 코드 주석을 따르십시오) 다음을 수행하려고 할 것입니다 :
페인트 이벤트 핸들러
[..]
QRect source(0, 0, 100, 100);
QRect target(0, 0, 400, 400);
// Calculate the point, where the image should be displayed.
// The center of source rect. should be in the center of target rect.
int deltaX = target.width() - source.width();
int deltaY = target.height() - source.height();
// Just apply coordinates transformation to draw where we need.
painter.translate(deltaX/2, deltaY/2);
painter.drawImage(source, img);
에서
// The image to draw - blue rectangle 100x100.
QImage img(100, 100, QImage::Format_ARGB32);
img.fill(Qt::blue);
을 그려 져야 샘플 이미지를 물론이 방법을 적용하기 전에 원본 사각형이 대상보다 작은 지 여부를 확인해야합니다. 간단하게 이미지를 가운데에 배치하는 방법을 보여주기 위해 코드를 생략했습니다.
2
화가는 크기가 없지만 그림은 device()
입니다. 당신은 당신이 당신의 이미지를 가운데에 맞출 사각형으로 QRect(painter.device()->width(), painter.device()->height())
사용할 수 있습니다
는 그런 다음과 같이 중앙에 이미지를 페인트 것 :.
QImage source;
QPainter painter(...);
...
QRect rect(source.rect());
QRect devRect(0, 0, painter.device()->width(), painter.device()->height());
rect.moveCenter(devRect.center());
painter.drawImage(rect.topLeft(), source);
1
내가 변수 이미지와보다 완벽한 예를 보여주고 싶었다 다른 위대한 답변에 추가하기 위해 제공된 영역의 범위 내에 머물러있는 크기.
void ImageView::paintEvent(QPaintEvent*)
{
if (this->imageBuffer.empty()){ return; }
double widgetWidth = this->width();
double widgetHeight = this->height();
QRectF target(0, 0, widgetWidth, widgetHeight);
QImage tempQImage = *this->imageBuffer.at(this->imageBuffer.count()-1);
tempQImage = tempQImage.scaled(rect().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
double imageSizeWidth = static_cast<double>(tempQImage.width());
double imageSizeHeight = static_cast<double>(tempQImage.height());
QRectF source(0.0, 0.0, imageSizeWidth, imageSizeHeight);
int deltaX = 0;
int deltaY = 0;
if(source.width() < target.width())
deltaX = target.width() - source.width();
else
deltaX = source.width() - target.width();
if(source.height() < target.height())
deltaY = target.height() - source.height();
else
deltaY = source.height() - target.height();
QPainter painter(this);
painter.translate(deltaX/2, deltaY/2);
painter.drawImage(source, tempQImage);
}