void StelDialog::setVisible(bool v) { if (v) { QSize screenSize = StelMainView::getInstance().size(); if (dialog) { dialog->show(); StelMainView::getInstance().scene()->setActiveWindow(proxy); // If the main window has been resized, it is possible the dialog // will be off screen. Check for this and move it to a visible // position if necessary QPointF newPos = proxy->pos(); if (newPos.x()>=screenSize.width()) newPos.setX(screenSize.width() - dialog->size().width()); if (newPos.y()>=screenSize.height()) newPos.setY(screenSize.height() - dialog->size().height()); if (newPos != dialog->pos()) proxy->setPos(newPos); proxy->setFocus(); return; } QGraphicsWidget* parent = qobject_cast<QGraphicsWidget*>(this->parent()); dialog = new QDialog(NULL); // dialog->setParent(parent); StelGui* gui = dynamic_cast<StelGui*>(StelApp::getInstance().getGui()); Q_ASSERT(gui); //dialog->setAttribute(Qt::WA_OpaquePaintEvent, true); connect(dialog, SIGNAL(rejected()), this, SLOT(close())); createDialogContent(); dialog->setStyleSheet(gui->getStelStyle().qtStyleSheet); // Ensure that tooltip get rendered in red in night mode. connect(&StelApp::getInstance(), SIGNAL(visionNightModeChanged(bool)), this, SLOT(updateNightModeProperty())); updateNightModeProperty(); proxy = new CustomProxy(parent, Qt::Tool); proxy->setWidget(dialog); QSizeF size = proxy->size(); // centre with dialog according to current window size. int newX = (int)((screenSize.width() - size.width())/2); int newY = (int)((screenSize.height() - size.height())/2); // Make sure that the window's title bar is accessible if (newY <-0) newY = 0; proxy->setPos(newX, newY); proxy->setWindowFrameMargins(2,0,2,2); // (this also changes the bounding rectangle size) // The caching is buggy on all plateforms with Qt 4.5.2 proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache); proxy->setZValue(100); StelMainView::getInstance().scene()->setActiveWindow(proxy); proxy->setFocus(); } else {
int main(int argc, char **argv) { if (argc < 4) { fprintf(stderr, "import <maps.json> <map id> <file.tif>\n"); return -1; } OGRRegisterAll(); GDALAllRegister(); QFile rootFile(argv[1]); QString mapId(argv[2]); QFileInfo filename(argv[3]); RootData rootData(NULL); Map *map = rootData.maps()[mapId]; Projection *pjGeo = Geographic::getProjection(NAD27); Projection *pj = map->projection(); readQuadIndex(0, "/Users/hawkinsp/geo/drg/index/drg100.shp", "drg100", pj); readQuadIndex(1, "/Users/hawkinsp/geo/drg/index/drg24.shp", "drg24", pj); // Index information seems buggy for these quads -- just use the regular grid. quads.remove("o37122g4"); // San Francisco North quads.remove("o37122g5"); // Point Bonita GDALDataset *ds = (GDALDataset *)GDALOpen(filename.filePath().toLatin1().data(), GA_ReadOnly); if (!ds) { fprintf(stderr, "ERROR: Could not open dataset.\n"); return -1; } const char *proj = ds->GetProjectionRef(); Quad quad; getQuadInfo(filename, pj, quad); // Read projection OGRSpatialReference srs; srs.importFromWkt((char **)&proj); // Size of the DRG QSize drgSize = QSize(ds->GetRasterXSize(), ds->GetRasterYSize()); printf("DRG id: %s, name %s, size %dx%d\n", quad.id.toLatin1().data(), quad.name.toLatin1().data(), drgSize.width(), drgSize.height()); // ------------------------------------------ // Read geotransform coefficients. The geotransform describe the mapping from // DRG image space to projection space. double geoTransformCoeff[6]; ds->GetGeoTransform(geoTransformCoeff); // Top left coordinate of the drg in projection space QPointF fProjTopLeft = QPointF(geoTransformCoeff[0], geoTransformCoeff[3]); // Size of a drg pixel in projection space QSizeF fPixelSize = QSizeF(geoTransformCoeff[1], geoTransformCoeff[5]); // Check Y pixel size is the negation of the X pixel size if (fabs(fPixelSize.width() + fPixelSize.height()) >= epsilon) { fprintf(stderr, "Invalid pixel sizes\n"); return -1; } // We assume the geotransform consists of only translation and scaling. // We'd need to do a more general image transformation to handle shearing. if (fabs(geoTransformCoeff[2]) >= epsilon || fabs(geoTransformCoeff[4]) >= epsilon) { fprintf(stderr, "ERROR: DRG geotransform has shear component.\n"); return -1; } // Transforms from drg space to projection space and vice versa QTransform drgProjTransform; drgProjTransform.translate(fProjTopLeft.x(), fProjTopLeft.y()); drgProjTransform.scale(fPixelSize.width(), fPixelSize.height()); QTransform projDrgTransform = drgProjTransform.inverted(); // Size of the DRG in projection space QSizeF fProjSize = QSizeF(qreal(ds->GetRasterXSize()) * fPixelSize.width(), qreal(ds->GetRasterYSize()) * fPixelSize.height()); QRectF projRect = QRectF(fProjTopLeft, fProjSize); // Rectangle covered by the entire map image QRectF mapRect = map->projToMap().mapRect(projRect); printf("Map Rect: %lf %lf %lf %lf\n", mapRect.left(), mapRect.top(), mapRect.right(), mapRect.bottom()); // Compute the initial scale factor and tile level QSizeF mapPixelSize = map->mapPixelSize(); assert(mapPixelSize.width() + mapPixelSize.height() < epsilon); QSizeF scale(fPixelSize.width() / mapPixelSize.width(), fPixelSize.height() / mapPixelSize.height()); int maxLevel = map->maxLevel(); while (scale.width() >= 1.1) { maxLevel--; scale /= 2.0; } // printf("scale %lf %lf\n", scale.width(), scale.height()); //return 0; // Compute the quad boundary QPolygonF projQuad(quad.boundary); QPolygonF geoQuad = pjGeo->transformFrom(pj, projQuad); QRectF geoQuadBounds(geoQuad.boundingRect()); printf("Series: %d %s\n", quad.series, map->layer(quad.series).name().toLatin1().data()); printf("Geographic quad boundary: %lf %lf %lf %lf\n", geoQuadBounds.left(), geoQuadBounds.top(), geoQuadBounds.right(), geoQuadBounds.bottom()); // Quad bounding rectangle in map space QRectF projQuadBounds = projQuad.boundingRect(); QRectF mapQuadBounds = map->projToMap().mapRect(projQuadBounds); printf("Quad bounding rectangle in map space: %lf %lf %lf %lf\n", mapQuadBounds.left(), mapQuadBounds.top(), mapQuadBounds.right(), mapQuadBounds.bottom()); // Quad bounding rectangle in drg space QPolygonF drgBounds = projDrgTransform.map(projQuad); QRectF drgQuadBounds = drgBounds.boundingRect(); printf("Quad bounding rectangle in drg space: %lf %lf %lf %lf\n", drgQuadBounds.left(), drgQuadBounds.top(), drgQuadBounds.right(), drgQuadBounds.bottom()); // Read the image QImage drg(filename.filePath()); if (drgQuadBounds.left() < -drgQuadSlackPixels || drgQuadBounds.right() > drgSize.width() + drgQuadSlackPixels || drgQuadBounds.top() < -drgQuadSlackPixels || drgQuadBounds.bottom() > drgSize.height() + drgQuadSlackPixels) { QString mfile("misalign-" + filename.baseName() + ".png"); fprintf(stderr, "WARNING: DRG and quadrangle boundaries are misaligned; diagnostic saved to '%s'!\n", mfile.toLatin1().data()); QImage image = drg.convertToFormat(QImage::Format_RGB32); QPainter p; p.begin(&image); QPainterPath pp; pp.addPolygon(drgBounds); p.setPen(QPen(Qt::blue, 2)); p.drawPath(pp); p.end(); image.save(mfile, "png"); } /*printf("top left %lf %lf\n", fProjTopLeft.x(), fProjTopLeft.y());*/ /*for (int i = 0; i< projectedQuad.size(); i++) { printf("quad proj %lf %lf\n", projectedQuad[i].x(), projectedQuad[i].y()); }*/ QDir dir; // for (int level = maxLevel; level >= 0; level--, scale /= 2.0) { int level = maxLevel; QSizeF rasterSizeF = QSizeF(ds->GetRasterXSize() * scale.width(), ds->GetRasterYSize() * scale.height()); QSize rasterSize = rasterSizeF.toSize(); printf("level %d size %dx%d\n", level, rasterSize.width(), rasterSize.height()); QImage drgScaled = drg.scaled(rasterSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); QPolygonF imageQuad; for (int i = 0; i < projQuad.size(); i++) { QPointF p = projQuad[i] - fProjTopLeft; imageQuad << QPointF(p.x() * scale.width() / fPixelSize.width(), p.y() * scale.height() / fPixelSize.height()); } QSizeF baseTileSize(map->baseTileSize(), map->baseTileSize()); int tileSize = map->tileSize(level); QRectF tileRectF = QRectF(mapQuadBounds.topLeft() / qreal(tileSize), mapQuadBounds.bottomRight() / qreal(tileSize)); QRect tileRect(QPoint(int(floor(tileRectF.left())), int(floor(tileRectF.top()))), QPoint(int(ceil(tileRectF.right())), int(ceil(tileRectF.bottom())))); /* printf("tile rect %d %d %d %d\n", tileRect.left(), tileRect.top(), tileRect.right(), tileRect.bottom());*/ for (int tileY = tileRect.top(); tileY <= tileRect.bottom(); tileY++) { for (int tileX = tileRect.left(); tileX <= tileRect.right(); tileX++) { Tile key(tileX, tileY, level, quad.series); QPointF tileTopLeft(tileX * tileSize, tileY * tileSize); QPointF deltaTileTopLeft = tileTopLeft - mapRect.topLeft(); qreal s = qreal(1 << (map->maxLevel() - level)); QPointF topLeft(deltaTileTopLeft.x() / s, deltaTileTopLeft.y() / s); QRectF src(topLeft, baseTileSize); QFileInfo tilePath(map->tilePath(key)); dir.mkpath(tilePath.path()); QImage image; if (tilePath.exists()) { QImage idxImage = QImage(tilePath.filePath()); image = idxImage.convertToFormat(QImage::Format_RGB32); } else { image = QImage(256, 256, QImage::Format_RGB32); image.setColorTable(drg.colorTable()); image.fill(QColor(255, 255, 255).rgb()); } QPainterPath pp; pp.addPolygon(imageQuad.translated(-topLeft)); QPainter painter; painter.begin(&image); painter.setClipPath(pp); painter.drawImage(-topLeft, drgScaled); // painter.setPen(QPen(QColor(0, 0, 255))); // painter.drawPath(pp); painter.end(); QImage tile = image.convertToFormat(QImage::Format_Indexed8, drg.colorTable(), Qt::ThresholdDither); tile.save(tilePath.filePath(), "png"); // printf("tile: %s\n", tilePath.filePath().toLatin1().data()); } } // } return 0; }
void PSV_TreeItem::paintLine(const QLineF &parentVLine, PSV_TreeItemData *itemData) { if(itemData == NULL) { return; } QPointF point2 = parentVLine.p2(); QList<PSV_TreeItemData*> children = itemData->children(); int leafCount = itemData->leafCount(); int count = children.count(); QPen pen; pen.setColor(QColor(Qt::red)); QPen pen_vLine; pen_vLine.setColor(QColor(Qt::blue)); QPen pen_hLine; QString tempText = itemData->text().trimmed(); QString text; for(int i = 0; i < tempText.length(); ++i) { text.append(tempText.at(i)); if(i != tempText.length() - 1) { text.append("\n"); } } QGraphicsItem* nodeItem = new QGraphicsEllipseItem(QRectF(0,0,1,1),this); nodeItem->setToolTip(tempText); QSizeF size = nodeItem->boundingRect().size(); nodeItem->setPos(point2.x() - size.width() * 0.5,point2.y() - size.height() * 0.5); QRectF rect = QRectF(nodeItem->pos().x(),nodeItem->pos().y(),size.width(),size.height()); // QGraphicsRectItem* rectItem = new QGraphicsRectItem(rect,this); // rectItem->setPen(pen); if(parentVLine.length() > PSV_ZEOR) { QLineF line = parentVLine; line.setP2(QPointF(line.x2(),rect.top())); QGraphicsLineItem* item = new QGraphicsLineItem(line,this); PSV_NOUSED(item); } if(count > 0) { QLineF leftHLine(point2.x() - leafCount * 0.5 * m_dw ,point2.y() ,rect.left() ,point2.y()); QLineF rightHLine(rect.right() ,point2.y() ,point2.x() + leafCount * 0.5 * m_dw ,point2.y()); double curX1 = leftHLine.x1(); for(int i = 0; i < count; ++i) { PSV_TreeItemData* tempItemData = children.at(i); int tempLeafCount = tempItemData->leafCount(); curX1 += tempLeafCount * 0.5 * m_dw; if(i == 0) { leftHLine.setP1(QPointF(curX1,leftHLine.y1())); } if(i == count - 1) { rightHLine.setP2(QPointF(curX1,leftHLine.y2())); } double y1 = point2.y(); double y2 = point2.y() + tempItemData->distance() * m_dhRatio; if(curX1 > rect.left() && curX1 < rect.right()) { y1 = rect.bottom(); } QLineF lineV(curX1,y1,curX1,y2); curX1 += tempLeafCount * 0.5 * m_dw; paintLine(lineV,tempItemData); } if(count > 1) { QGraphicsLineItem* leftHLineItem = new QGraphicsLineItem(leftHLine,this); leftHLineItem->setPen(pen_hLine); QGraphicsLineItem* rightHLineItem = new QGraphicsLineItem(rightHLine,this); rightHLineItem->setPen(pen_hLine); } } }
void SvgParser::applyFillStyle(KoShape *shape) { SvgGraphicsContext *gc = m_context.currentGC(); if (! gc) return; if (gc->fillType == SvgGraphicsContext::None) { shape->setBackground(QSharedPointer<KoShapeBackground>(0)); } else if (gc->fillType == SvgGraphicsContext::Solid) { shape->setBackground(QSharedPointer<KoColorBackground>(new KoColorBackground(gc->fillColor))); } else if (gc->fillType == SvgGraphicsContext::Complex) { // try to find referenced gradient SvgGradientHelper *gradient = findGradient(gc->fillId); if (gradient) { // great, we have a gradient fill QSharedPointer<KoGradientBackground> bg; if (gradient->gradientUnits() == SvgGradientHelper::ObjectBoundingBox) { bg = QSharedPointer<KoGradientBackground>(new KoGradientBackground(*gradient->gradient())); bg->setTransform(gradient->transform()); } else { QGradient *convertedGradient = SvgGradientHelper::convertGradient(gradient->gradient(), shape->size()); bg = QSharedPointer<KoGradientBackground>(new KoGradientBackground(convertedGradient)); QTransform invShapematrix = shape->transformation().inverted(); bg->setTransform(gradient->transform() * gc->matrix * invShapematrix); } shape->setBackground(bg); } else { // try to find referenced pattern SvgPatternHelper *pattern = findPattern(gc->fillId); KoImageCollection *imageCollection = m_documentResourceManager->imageCollection(); if (pattern && imageCollection) { // great we have a pattern fill QRectF objectBound = QRectF(QPoint(), shape->size()); QRectF currentBoundbox = gc->currentBoundbox; // properties from the object are not inherited // so we are creating a new context without copying SvgGraphicsContext *gc = m_context.pushGraphicsContext(pattern->content(), false); // the pattern establishes a new coordinate system with its // origin at the patterns x and y attributes gc->matrix = QTransform(); // object bounding box units are relative to the object the pattern is applied if (pattern->patternContentUnits() == SvgPatternHelper::ObjectBoundingBox) { gc->currentBoundbox = objectBound; gc->forcePercentage = true; } else { // inherit the current bounding box gc->currentBoundbox = currentBoundbox; } applyStyle(0, pattern->content()); // parse the pattern content elements QList<KoShape*> patternContent = parseContainer(pattern->content()); // generate the pattern image from the shapes and the object bounding rect QImage image = pattern->generateImage(objectBound, patternContent); m_context.popGraphicsContext(); // delete the shapes created from the pattern content qDeleteAll(patternContent); if (!image.isNull()) { QSharedPointer<KoPatternBackground> bg(new KoPatternBackground(imageCollection)); bg->setPattern(image); QPointF refPoint = shape->documentToShape(pattern->position(objectBound)); QSizeF tileSize = pattern->size(objectBound); bg->setPatternDisplaySize(tileSize); if (pattern->patternUnits() == SvgPatternHelper::ObjectBoundingBox) { if (tileSize == objectBound.size()) bg->setRepeat(KoPatternBackground::Stretched); } // calculate pattern reference point offset in percent of tileSize // and relative to the topleft corner of the shape qreal fx = refPoint.x() / tileSize.width(); qreal fy = refPoint.y() / tileSize.height(); if (fx < 0.0) fx = floor(fx); else if (fx > 1.0) fx = ceil(fx); else fx = 0.0; if (fy < 0.0) fy = floor(fy); else if (fx > 1.0) fy = ceil(fy); else fy = 0.0; qreal offsetX = 100.0 * (refPoint.x() - fx * tileSize.width()) / tileSize.width(); qreal offsetY = 100.0 * (refPoint.y() - fy * tileSize.height()) / tileSize.height(); bg->setReferencePointOffset(QPointF(offsetX, offsetY)); shape->setBackground(bg); } } else { // no referenced fill found, use fallback color shape->setBackground(QSharedPointer<KoColorBackground>(new KoColorBackground(gc->fillColor))); } } } KoPathShape *path = dynamic_cast<KoPathShape*>(shape); if (path) path->setFillRule(gc->fillRule); }
QTCEXPORT(void,qtc_QSizeF_expandedTo_qth)(void* x0, double x1_w, double x1_h, double* _ret_w, double* _ret_h) { QSizeF tx1(x1_w, x1_h); QSizeF tc = ((QSizeF*)x0)->expandedTo(tx1); *_ret_w = tc.width(); *_ret_h = tc.height(); return; }
QSizeF niceInterval(QSizeF interval) { return QSizeF(niceInterval(interval.width()), niceInterval(interval.height())); }
MLWebKit::MLWebKit(int overscanw, int overscanh, qreal zoom, int rotationMode) { #ifdef _INSPECTOR_ pWebKit = this; #endif // Create elements pScene = new QGraphicsScene(); if ( pScene == NULL ) return; pView = new QGraphicsView(pScene); pWebview = new GraphicsWebView(); pPage = new WebPage(); pFrame = pPage->mainFrame(); QApplication* pApp = (QApplication *)QApplication::instance(); QDesktopWidget* pDesktop = QApplication::desktop(); if ( pScene == NULL || pView == NULL || pWebview == NULL || pPage == NULL || pFrame == NULL || pApp == NULL || pDesktop == NULL ) { qDebug () << "unable to construct browser (elements)"; return; } // Rotate View according to rotationMode pView->rotate(90*rotationMode); #ifdef QT_OPENGL_LIB pWidget = NULL; // pWidget = new QGLWidget(); // pWidget = new QGLWidget(pView); #endif #ifdef _INSPECTOR_ pInspector = new QWebInspector; pInspector->setPage(pPage); pInspector->resize(QApplication::desktop()->screenGeometry().size()); #endif // Configuration, settings and alike // pScene->setItemIndexMethod( QGraphicsScene::NoIndex); // pView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); pView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); // pView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate); // pView->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); // Disable some 'browser features / elements' pView->setFrameShape(QFrame::NoFrame); pView->setHorizontalScrollBarPolicy ( Qt::ScrollBarAlwaysOff ); pView->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff ); // pView->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); pView->setWindowFlags(Qt::FramelessWindowHint); pView->showFullScreen(); // Overrule the 'foreground' and 'background' defaults with transparent colors QPalette palette; palette.setBrush(QPalette::Active, QPalette::Window, Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::Base, Qt::SolidPattern); palette.setBrush(QPalette::Inactive, QPalette::Window, Qt::SolidPattern); palette.setBrush(QPalette::Inactive, QPalette::Base, Qt::SolidPattern); palette.setColor(QPalette::Active, QPalette::Window, QColor(0, 0, 0x80, 255)); // Nice light grey default backgroundcolor. Change to bright red if you want to see overscan borders. palette.setColor(QPalette::Active, QPalette::Base, QColor(0xC0, 0xc0, 0xc0, 255)); palette.setColor(QPalette::Inactive, QPalette::Window, QColor(0, 0, 0, 255)); palette.setColor(QPalette::Inactive, QPalette::Base, QColor(0, 0, 0, 255)); pApp->setPalette(palette); //TODO: implement check QSizeF screenSize = pDesktop->screenGeometry().size(); qDebug () << "screen geometry : " << screenSize; QSizeF displaySize; switch (rotationMode) { break; case 1: case 3: displaySize = QSizeF( screenSize.height() - overscanw, screenSize.width() - overscanh ); break; case 0: case 2: default: displaySize = QSizeF( screenSize.width() - overscanw, screenSize.height() - overscanh ); } qDebug () << "display geometry : " << displaySize; pWebview->resize(displaySize); pWebview->setPage(pPage); // Set the keyboard and mouse focus pWebview->setFocus(); // Some extra settings QWebSettings* pSettings = pWebview->settings(); #ifdef _INSPECTOR_ pSettings->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); #endif pSettings->setAttribute(QWebSettings::AcceleratedCompositingEnabled, true); pSettings->setAttribute(QWebSettings::WebGLEnabled, false); pSettings->setAttribute(QWebSettings::PluginsEnabled, false); pSettings->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, true); pSettings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true); pSettings->setAttribute(QWebSettings::LocalContentCanAccessFileUrls, true); // pSettings->setAttribute(QWebSettings::FrameFlatteningEnabled, true); pSettings->setAttribute(QWebSettings::LocalStorageEnabled, true); // pSettings->setAttribute(QWebSettings::WebSecurityEnabled, false); pSettings->setAttribute(QWebSettings::SpatialNavigationEnabled, false); // Overrule the cache settings /* pSettings->setMaximumPagesInCache(0); pSettings->setObjectCacheCapacities(0, 0, 0); pSettings->QWebSettings::clearMemoryCaches(); */ // Finalize #ifdef QT_OPENGL_LIB // pView->setViewport(pWidget); pView->setViewport(new QGLWidget(QGL::DirectRendering | QGL::DoubleBuffer)); #endif pScene->addItem(pWebview); #ifdef _INSPECTOR_ pProxyWidget = pScene->addWidget(pInspector); #endif // Set visibility #ifdef _INSPECTOR_ // pInspector->hide(); pProxyWidget->hide(); #endif // Set zoomfactor. (help readability) pWebview->setZoomFactor(zoom); //pWebview->setTextSizeMultiplier(zoom); pWebview->show(); }
QImage RichTextRenderer::renderText() { // qDebug()<<itemName()<<"TextBoxWarmingThread::run(): htmlCode:"<<htmlCode; //qDebug() << "RichTextRenderer::renderText(): HTML:"<<html(); //qDebug() << "RichTextRenderer::update(): Update Start..."; //qDebug() << "RichTextRenderer::renderText(): \t in thread:"<<QThread::currentThreadId(); if(m_updateTimer.isActive()) m_updateTimer.stop(); QTime renderTime; renderTime.start(); QTextDocument doc; QTextDocument shadowDoc; if (Qt::mightBeRichText(html())) { doc.setHtml(html()); shadowDoc.setHtml(html()); } else { doc.setPlainText(html()); shadowDoc.setPlainText(html()); } int textWidth = m_textWidth; doc.setTextWidth(textWidth); shadowDoc.setTextWidth(textWidth); // Apply outline pen to the html QTextCursor cursor(&doc); cursor.select(QTextCursor::Document); QTextCharFormat format; QPen p(Qt::NoPen); if(outlineEnabled()) { p = outlinePen(); p.setJoinStyle(Qt::MiterJoin); } format.setTextOutline(p); //format.setForeground(fillEnabled() ? fillBrush() : Qt::NoBrush); //Qt::white); cursor.mergeCharFormat(format); // Setup the shadow text formatting if enabled if(shadowEnabled()) { if(shadowBlurRadius() <= 0.05) { QTextCursor cursor(&shadowDoc); cursor.select(QTextCursor::Document); QTextCharFormat format; format.setTextOutline(Qt::NoPen); format.setForeground(shadowBrush()); cursor.mergeCharFormat(format); } } QSizeF shadowSize = shadowEnabled() ? QSizeF(shadowOffsetX(),shadowOffsetY()) : QSizeF(0,0); QSizeF docSize = doc.size(); QSizeF padSize(12.,12.); QSizeF sumSize = (docSize + shadowSize + padSize);//.toSize(); QSizeF scaledSize = QSizeF(sumSize.width() * m_scaling.x(), sumSize.height() * m_scaling.y()); if(m_scaling.x() != 1. || m_scaling.y() != 1.) { //qDebug() << "RichTextRenderer::renderText(): Orig size:"<<sumSize<<", scaled size:"<<scaledSize<<", scaling:"<<m_scaling; m_rawSize = sumSize; } //qDebug() << "RichTextRenderer::update(): textWidth: "<<textWidth<<", shadowSize:"<<shadowSize<<", docSize:"<<docSize<<", sumSize:"<<sumSize; QImage cache(scaledSize.toSize(),QImage::Format_ARGB32); //_Premultiplied); memset(cache.scanLine(0),0,cache.byteCount()); double padSizeHalfX = padSize.width() / 2; double padSizeHalfY = padSize.height() / 2; QPainter textPainter(&cache); textPainter.scale(m_scaling.x(), m_scaling.y()); //textPainter.fillRect(cache.rect(),Qt::transparent); QAbstractTextDocumentLayout::PaintContext pCtx; //qDebug() << "RichTextRenderer::renderText(): shadowEnabled():"<<shadowEnabled()<<", shadowBlurRadius():"<<shadowBlurRadius(); if(shadowEnabled()) { if(shadowBlurRadius() <= 0.05) { // render a "cheap" version of the shadow using the shadow text document textPainter.save(); textPainter.translate(shadowOffsetX(),shadowOffsetY()); shadowDoc.documentLayout()->draw(&textPainter, pCtx); textPainter.restore(); } else { double radius = shadowBlurRadius(); // create temporary pixmap to hold a copy of the text QSizeF blurSize = ImageFilters::blurredSizeFor(doc.size(), (int)radius); QSizeF scaledBlurSize = QSize(blurSize.width() * m_scaling.x(), blurSize.height() * m_scaling.y()); //QSize docSize = doc.size(); //qDebug() << "RichTextRenderer::renderText(): [shadow] radius:"<<radius<<" blurSize:"<<blurSize<<", scaling:"<<m_scaling<<", scaledBlurSize:"<<scaledBlurSize; //qDebug() << "Blur size:"<<blurSize<<", doc:"<<doc.size()<<", radius:"<<radius; QImage tmpImage(scaledBlurSize.toSize(),QImage::Format_ARGB32_Premultiplied); memset(tmpImage.scanLine(0),0,tmpImage.byteCount()); // render the text QPainter tmpPainter(&tmpImage); tmpPainter.scale(m_scaling.x(), m_scaling.y()); tmpPainter.save(); tmpPainter.translate(radius + padSizeHalfX, radius + padSizeHalfY); doc.documentLayout()->draw(&tmpPainter, pCtx); tmpPainter.restore(); // blacken the text by applying a color to the copy using a QPainter::CompositionMode_DestinationIn operation. // This produces a homogeneously-colored pixmap. QRect rect = tmpImage.rect(); tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); tmpPainter.fillRect(rect, shadowBrush().color()); tmpPainter.end(); // blur the colored text ImageFilters::blurImage(tmpImage, (int)radius); // render the blurred text at an offset into the cache textPainter.save(); textPainter.translate(shadowOffsetX() - radius, shadowOffsetY() - radius); textPainter.drawImage(0, 0, tmpImage); textPainter.restore(); } } textPainter.translate(padSizeHalfX, padSizeHalfY); doc.documentLayout()->draw(&textPainter, pCtx); textPainter.end(); m_image = cache.convertToFormat(QImage::Format_ARGB32); emit textRendered(m_image); //qDebug() << "RichTextRenderer::renderText(): Render finished, elapsed:"<<renderTime.elapsed()<<"ms"; //m_image.save("debug-text.png"); return m_image; }
void MainView2D::createFixtureItem(quint32 fxID, quint16 headIndex, quint16 linkedIndex, QVector3D pos, bool mmCoords) { if (isEnabled() == false) return; if (m_gridItem == NULL) initialize2DProperties(); qDebug() << "[MainView2D] Creating fixture with ID" << fxID << headIndex << linkedIndex << "pos:" << pos; Fixture *fixture = m_doc->fixture(fxID); if (fixture == NULL) return; quint32 itemID = FixtureUtils::fixtureItemID(fxID, headIndex, linkedIndex); QLCFixtureMode *fxMode = fixture->fixtureMode(); QQuickItem *newFixtureItem = qobject_cast<QQuickItem*>(fixtureComponent->create()); quint32 itemFlags = m_monProps->fixtureFlags(fxID, headIndex, linkedIndex); newFixtureItem->setParentItem(m_gridItem); newFixtureItem->setProperty("itemID", itemID); if (itemFlags & MonitorProperties::HiddenFlag) newFixtureItem->setProperty("visible", false); if (fxMode != NULL && fixture->type() != QLCFixtureDef::Dimmer) { QLCPhysical phy = fxMode->physical(); //qDebug() << "Current mode fixture heads:" << fxMode->heads().count(); newFixtureItem->setProperty("headsNumber", fxMode->heads().count()); if (fixture->channelNumber(QLCChannel::Pan, QLCChannel::MSB) != QLCChannel::invalid()) { int panDeg = phy.focusPanMax(); if (panDeg == 0) panDeg = 360; newFixtureItem->setProperty("panMaxDegrees", panDeg); } if (fixture->channelNumber(QLCChannel::Tilt, QLCChannel::MSB) != QLCChannel::invalid()) { int tiltDeg = phy.focusTiltMax(); if (tiltDeg == 0) tiltDeg = 270; newFixtureItem->setProperty("tiltMaxDegrees", tiltDeg); } } QPointF itemPos; QSizeF size = FixtureUtils::item2DDimension(fixture->type() == QLCFixtureDef::Dimmer ? NULL : fxMode, m_monProps->pointOfView()); if (mmCoords == false && (pos.x() != 0 || pos.y() != 0)) { float gridUnits = m_monProps->gridUnits() == MonitorProperties::Meters ? 1000.0 : 304.8; itemPos.setX((pos.x() * gridUnits) / m_cellPixels); itemPos.setY((pos.y() * gridUnits) / m_cellPixels); } if (m_monProps->containsItem(fxID, headIndex, linkedIndex)) { itemPos = FixtureUtils::item2DPosition(m_monProps, m_monProps->pointOfView(), pos); newFixtureItem->setProperty("rotation", FixtureUtils::item2DRotation(m_monProps->pointOfView(), m_monProps->fixtureRotation(fxID, headIndex, linkedIndex))); } else { itemPos = FixtureUtils::available2DPosition(m_doc, m_monProps->pointOfView(), QRectF(itemPos.x(), itemPos.y(), size.width(), size.height())); // add the new fixture to the Doc monitor properties QVector3D newPos = FixtureUtils::item3DPosition(m_monProps, itemPos, 1000.0); m_monProps->setFixturePosition(fxID, headIndex, linkedIndex, newPos); m_monProps->setFixtureFlags(fxID, headIndex, linkedIndex, 0); Tardis::instance()->enqueueAction(Tardis::FixtureSetPosition, itemID, QVariant(QVector3D(0, 0, 0)), QVariant(newPos)); } newFixtureItem->setProperty("mmXPos", itemPos.x()); newFixtureItem->setProperty("mmYPos", itemPos.y()); newFixtureItem->setProperty("mmWidth", size.width()); newFixtureItem->setProperty("mmHeight", size.height()); newFixtureItem->setProperty("fixtureName", fixture->name()); // and finally add the new item to the items map m_itemsMap[itemID] = newFixtureItem; QByteArray values; updateFixture(fixture, values); }
QRectF SCgVisualControl::boundingRect() const { QSizeF size = baseObject()->size(); return QRectF(-size.width() / 2.f, -size.height() / 2.f, size.width(), size.height()); }
/*! \return Icon representing the curve on the legend \param index Index of the legend entry ( ignored as there is only one ) \param size Icon size \sa QwtPlotItem::setLegendIconSize(), QwtPlotItem::legendData() */ QwtGraphic QwtPlotCurve::legendIcon( int index, const QSizeF &size ) const { Q_UNUSED( index ); if ( size.isEmpty() ) return QwtGraphic(); QwtGraphic graphic; graphic.setDefaultSize( size ); graphic.setRenderHint( QwtGraphic::RenderPensUnscaled, true ); QPainter painter( &graphic ); painter.setRenderHint( QPainter::Antialiasing, testRenderHint( QwtPlotItem::RenderAntialiased ) ); if ( d_data->legendAttributes == 0 || d_data->legendAttributes & QwtPlotCurve::LegendShowBrush ) { QBrush brush = d_data->brush; if ( brush.style() == Qt::NoBrush && d_data->legendAttributes == 0 ) { if ( style() != QwtPlotCurve::NoCurve ) { brush = QBrush( pen().color() ); } else if ( d_data->symbol && ( d_data->symbol->style() != QwtSymbol::NoSymbol ) ) { brush = QBrush( d_data->symbol->pen().color() ); } } if ( brush.style() != Qt::NoBrush ) { QRectF r( 0, 0, size.width(), size.height() ); painter.fillRect( r, brush ); } } if ( d_data->legendAttributes & QwtPlotCurve::LegendShowLine ) { if ( pen() != Qt::NoPen ) { QPen pn = pen(); pn.setCapStyle( Qt::FlatCap ); painter.setPen( pn ); const double y = 0.5 * size.height(); QwtPainter::drawLine( &painter, 0.0, y, size.width(), y ); } } if ( d_data->legendAttributes & QwtPlotCurve::LegendShowSymbol ) { if ( d_data->symbol ) { QRectF r( 0, 0, size.width(), size.height() ); d_data->symbol->drawSymbol( &painter, r ); } } return graphic; }
QRectF DebugPropertyItem::boundingRect() const { qreal penWidth = 1; QSizeF size = _info.size(); QRectF bnds(-5 - (penWidth / 2), - 5 - (penWidth / 2), size.width() + 10 + penWidth, size.height() + 10 + penWidth); return bnds; }
void IncompleteThumbnail::drawQuestionMark(QPainter& painter, QRectF const& bounding_rect) { QString const text(QString::fromAscii("?")); // Because painting happens only from the main thread, we don't // need to care about concurrent access. if (m_sCachedPath.isEmpty()) { #if 0 QFont font(painter.font()); font.setWeight(QFont::DemiBold); font.setStyleStrategy(QFont::ForceOutline); m_sCachedPath.addText(0, 0, font, text); #else m_sCachedPath.moveTo(QPointF(4.42188, -2.40625)); m_sCachedPath.cubicTo( QPointF(4.42188, -3.20312), QPointF(4.51562, -3.32812), QPointF(5.23438, -3.84375) ); m_sCachedPath.cubicTo( QPointF(6.34375, -4.625), QPointF(6.67188, -5.15625), QPointF(6.67188, -6.17188) ); m_sCachedPath.cubicTo( QPointF(6.67188, -7.79688), QPointF(5.4375, -8.92188), QPointF(3.6875, -8.92188) ); m_sCachedPath.cubicTo( QPointF(2.65625, -8.92188), QPointF(1.84375, -8.5625), QPointF(1.32812, -7.85938) ); m_sCachedPath.cubicTo( QPointF(0.9375, -7.32812), QPointF(0.78125, -6.75), QPointF(0.765625, -5.76562) ); m_sCachedPath.lineTo(QPointF(2.40625, -5.76562)); m_sCachedPath.lineTo(QPointF(2.40625, -5.79688)); m_sCachedPath.cubicTo( QPointF(2.34375, -6.76562), QPointF(2.92188, -7.51562), QPointF(3.71875, -7.51562) ); m_sCachedPath.cubicTo( QPointF(4.4375, -7.51562), QPointF(4.98438, -6.90625), QPointF(4.98438, -6.125) ); m_sCachedPath.cubicTo( QPointF(4.98438, -5.59375), QPointF(4.82812, -5.35938), QPointF(4.125, -4.78125) ); m_sCachedPath.cubicTo( QPointF(3.17188, -3.96875), QPointF(2.90625, -3.4375), QPointF(2.9375, -2.40625) ); m_sCachedPath.lineTo(QPointF(4.42188, -2.40625)); m_sCachedPath.moveTo(QPointF(4.625, -1.75)); m_sCachedPath.lineTo(QPointF(2.8125, -1.75)); m_sCachedPath.lineTo(QPointF(2.8125, 0.0)); m_sCachedPath.lineTo(QPointF(4.625, 0.0)); m_sCachedPath.lineTo(QPointF(4.625, -1.75)); #endif } QRectF const text_rect(m_sCachedPath.boundingRect()); QTransform xform1; xform1.translate(-text_rect.left(), -text_rect.top()); QSizeF const unscaled_size(text_rect.size()); QSizeF scaled_size(unscaled_size); scaled_size.scale(bounding_rect.size() * 0.9, Qt::KeepAspectRatio); double const hscale = scaled_size.width() / unscaled_size.width(); double const vscale = scaled_size.height() / unscaled_size.height(); QTransform xform2; xform2.scale(hscale, vscale); // Position the text at the center of our bounding rect. QSizeF const translation(bounding_rect.size() * 0.5 - scaled_size * 0.5); QTransform xform3; xform3.translate(translation.width(), translation.height()); painter.setWorldTransform(xform1 * xform2 * xform3, true); painter.setRenderHint(QPainter::Antialiasing); QPen pen(QColor(0x00, 0x00, 0x00, 60)); pen.setWidth(2); pen.setCosmetic(true); painter.setPen(pen); painter.drawPath(m_sCachedPath); }
void QSvgText::draw(QPainter *p, QSvgExtraStates &states) { applyStyle(p, states); qreal oldOpacity = p->opacity(); p->setOpacity(oldOpacity * states.fillOpacity); // Force the font to have a size of 100 pixels to avoid truncation problems // when the font is very small. qreal scale = 100.0 / p->font().pointSizeF(); Qt::Alignment alignment = states.textAnchor; QTransform oldTransform = p->worldTransform(); p->scale(1 / scale, 1 / scale); qreal y = 0; bool initial = true; qreal px = m_coord.x() * scale; qreal py = m_coord.y() * scale; QSizeF scaledSize = m_size * scale; if (m_type == TEXTAREA) { if (alignment == Qt::AlignHCenter) px += scaledSize.width() / 2; else if (alignment == Qt::AlignRight) px += scaledSize.width(); } QRectF bounds; if (m_size.height() != 0) bounds = QRectF(0, py, 1, scaledSize.height()); // x and width are not used. bool appendSpace = false; QVector<QString> paragraphs; QStack<QTextCharFormat> formats; QVector<QList<QTextLayout::FormatRange> > formatRanges; paragraphs.push_back(QString()); formatRanges.push_back(QList<QTextLayout::FormatRange>()); for (int i = 0; i < m_tspans.size(); ++i) { if (m_tspans[i] == LINEBREAK) { if (m_type == TEXTAREA) { if (paragraphs.back().isEmpty()) { QFont font = p->font(); font.setPixelSize(font.pointSizeF() * scale); QTextLayout::FormatRange range; range.start = 0; range.length = 1; range.format.setFont(font); formatRanges.back().append(range); paragraphs.back().append(QLatin1Char(' '));; } appendSpace = false; paragraphs.push_back(QString()); formatRanges.push_back(QList<QTextLayout::FormatRange>()); } } else { WhitespaceMode mode = m_tspans[i]->whitespaceMode(); m_tspans[i]->applyStyle(p, states); QFont font = p->font(); font.setPixelSize(font.pointSizeF() * scale); QString newText(m_tspans[i]->text()); newText.replace(QLatin1Char('\t'), QLatin1Char(' ')); newText.replace(QLatin1Char('\n'), QLatin1Char(' ')); bool prependSpace = !appendSpace && !m_tspans[i]->isTspan() && (mode == Default) && !paragraphs.back().isEmpty() && newText.startsWith(QLatin1Char(' ')); if (appendSpace || prependSpace) paragraphs.back().append(QLatin1Char(' ')); bool appendSpaceNext = (!m_tspans[i]->isTspan() && (mode == Default) && newText.endsWith(QLatin1Char(' '))); if (mode == Default) { newText = newText.simplified(); if (newText.isEmpty()) appendSpaceNext = false; } QTextLayout::FormatRange range; range.start = paragraphs.back().length(); range.length = newText.length(); range.format.setFont(font); range.format.setTextOutline(p->pen()); range.format.setForeground(p->brush()); if (appendSpace) { Q_ASSERT(!formatRanges.back().isEmpty()); ++formatRanges.back().back().length; } else if (prependSpace) { --range.start; ++range.length; } formatRanges.back().append(range); appendSpace = appendSpaceNext; paragraphs.back() += newText; m_tspans[i]->revertStyle(p, states); } } if (states.svgFont) { // SVG fonts not fully supported... QString text = paragraphs.front(); for (int i = 1; i < paragraphs.size(); ++i) { text.append(QLatin1Char('\n')); text.append(paragraphs[i]); } states.svgFont->draw(p, m_coord * scale, text, p->font().pointSizeF() * scale, states.textAnchor); } else { for (int i = 0; i < paragraphs.size(); ++i) { QTextLayout tl(paragraphs[i]); QTextOption op = tl.textOption(); op.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); tl.setTextOption(op); tl.setAdditionalFormats(formatRanges[i]); tl.beginLayout(); forever { QTextLine line = tl.createLine(); if (!line.isValid()) break; if (m_size.width() != 0) line.setLineWidth(scaledSize.width()); } tl.endLayout(); bool endOfBoundsReached = false; for (int i = 0; i < tl.lineCount(); ++i) { QTextLine line = tl.lineAt(i); qreal x = 0; if (alignment == Qt::AlignHCenter) x -= 0.5 * line.naturalTextWidth(); else if (alignment == Qt::AlignRight) x -= line.naturalTextWidth(); if (initial && m_type == TEXT) y -= line.ascent(); initial = false; line.setPosition(QPointF(x, y)); // Check if the current line fits into the bounding rectangle. if ((m_size.width() != 0 && line.naturalTextWidth() > scaledSize.width()) || (m_size.height() != 0 && y + line.height() > scaledSize.height())) { // I need to set the bounds height to 'y-epsilon' to avoid drawing the current // line. Since the font is scaled to 100 units, 1 should be a safe epsilon. bounds.setHeight(y - 1); endOfBoundsReached = true; break; } y += 1.1 * line.height(); } tl.draw(p, QPointF(px, py), QVector<QTextLayout::FormatRange>(), bounds); if (endOfBoundsReached) break; } } p->setWorldTransform(oldTransform, false); p->setOpacity(oldOpacity); revertStyle(p, states); }
void QgsPalLabeling::registerDiagramFeature( QgsVectorLayer* layer, QgsFeature& feat, const QgsRenderContext& context ) { //get diagram layer settings, diagram renderer QHash<QgsVectorLayer*, QgsDiagramLayerSettings>::iterator layerIt = mActiveDiagramLayers.find( layer ); if ( layerIt == mActiveDiagramLayers.constEnd() ) { return; } //convert geom to geos QgsGeometry* geom = feat.geometry(); if ( layerIt.value().ct && !willUseLayer( layer ) ) // reproject the geometry if feature not already transformed for labeling { geom->transform( *( layerIt.value().ct ) ); } GEOSGeometry* geos_geom = geom->asGeos(); if ( geos_geom == 0 ) { return; // invalid geometry } //create PALGeometry with diagram = true QgsPalGeometry* lbl = new QgsPalGeometry( feat.id(), "", GEOSGeom_clone( geos_geom ) ); lbl->setIsDiagram( true ); // record the created geometry - it will be deleted at the end. layerIt.value().geometries.append( lbl ); double diagramWidth = 0; double diagramHeight = 0; QgsDiagramRendererV2* dr = layerIt.value().renderer; if ( dr ) { QSizeF diagSize = dr->sizeMapUnits( feat.attributeMap(), context ); if ( diagSize.isValid() ) { diagramWidth = diagSize.width(); diagramHeight = diagSize.height(); } //append the diagram attributes to lbl QList<int> diagramAttrib = dr->diagramAttributes(); QList<int>::const_iterator diagAttIt = diagramAttrib.constBegin(); for ( ; diagAttIt != diagramAttrib.constEnd(); ++diagAttIt ) { lbl->addDiagramAttribute( *diagAttIt, feat.attributeMap()[*diagAttIt] ); } } // register feature to the layer int ddColX = layerIt.value().xPosColumn; int ddColY = layerIt.value().yPosColumn; double ddPosX = 0.0; double ddPosY = 0.0; bool ddPos = ( ddColX >= 0 && ddColY >= 0 ); if ( ddPos ) { bool posXOk, posYOk; //data defined diagram position is always centered ddPosX = feat.attributeMap()[ddColX].toDouble( &posXOk ) - diagramWidth / 2.0; ddPosY = feat.attributeMap()[ddColY].toDouble( &posYOk ) - diagramHeight / 2.0; if ( !posXOk || !posYOk ) { ddPos = false; } else { const QgsCoordinateTransform* ct = layerIt.value().ct; if ( ct ) { double z = 0; ct->transformInPlace( ddPosX, ddPosY, z ); } } } try { if ( !layerIt.value().palLayer->registerFeature( lbl->strId(), lbl, diagramWidth, diagramHeight, "", ddPosX, ddPosY, ddPos ) ) { return; } } catch ( std::exception &e ) { Q_UNUSED( e ); QgsDebugMsg( QString( "Ignoring feature %1 due PAL exception: " ).arg( feat.id() ) + QString::fromLatin1( e.what() ) ); return; } pal::Feature* palFeat = layerIt.value().palLayer->getFeature( lbl->strId() ); QgsPoint ptZero = layerIt.value().xform->toMapCoordinates( 0, 0 ); QgsPoint ptOne = layerIt.value().xform->toMapCoordinates( 1, 0 ); palFeat->setDistLabel( qAbs( ptOne.x() - ptZero.x() ) * layerIt.value().dist ); }
void QItemDelegate::drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const { Q_D(const QItemDelegate); QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if (cg == QPalette::Normal && !(option.state & QStyle::State_Active)) cg = QPalette::Inactive; if (option.state & QStyle::State_Selected) { painter->fillRect(rect, option.palette.brush(cg, QPalette::Highlight)); painter->setPen(option.palette.color(cg, QPalette::HighlightedText)); } else { painter->setPen(option.palette.color(cg, QPalette::Text)); } if (text.isEmpty()) return; if (option.state & QStyle::State_Editing) { painter->save(); painter->setPen(option.palette.color(cg, QPalette::Text)); painter->drawRect(rect.adjusted(0, 0, -1, -1)); painter->restore(); } const QStyleOptionViewItem opt = option; const QWidget *widget = d->widget(option); QStyle *style = widget ? widget->style() : QApplication::style(); const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, widget) + 1; QRect textRect = rect.adjusted(textMargin, 0, -textMargin, 0); // remove width padding const bool wrapText = opt.features & QStyleOptionViewItem::WrapText; d->textOption.setWrapMode(wrapText ? QTextOption::WordWrap : QTextOption::ManualWrap); d->textOption.setTextDirection(option.direction); d->textOption.setAlignment(QStyle::visualAlignment(option.direction, option.displayAlignment)); d->textLayout.setTextOption(d->textOption); d->textLayout.setFont(option.font); d->textLayout.setText(QItemDelegatePrivate::replaceNewLine(text)); QSizeF textLayoutSize = d->doTextLayout(textRect.width()); if (textRect.width() < textLayoutSize.width() || textRect.height() < textLayoutSize.height()) { QString elided; int start = 0; int end = text.indexOf(QChar::LineSeparator, start); if (end == -1) { elided += option.fontMetrics.elidedText(text, option.textElideMode, textRect.width()); } else { while (end != -1) { elided += option.fontMetrics.elidedText(text.mid(start, end - start), option.textElideMode, textRect.width()); elided += QChar::LineSeparator; start = end + 1; end = text.indexOf(QChar::LineSeparator, start); } //let's add the last line (after the last QChar::LineSeparator) elided += option.fontMetrics.elidedText(text.mid(start), option.textElideMode, textRect.width()); } d->textLayout.setText(elided); textLayoutSize = d->doTextLayout(textRect.width()); } const QSize layoutSize(textRect.width(), int(textLayoutSize.height())); const QRect layoutRect = QStyle::alignedRect(option.direction, option.displayAlignment, layoutSize, textRect); // if we still overflow even after eliding the text, enable clipping if (!hasClipping() && (textRect.width() < textLayoutSize.width() || textRect.height() < textLayoutSize.height())) { painter->save(); painter->setClipRect(layoutRect); d->textLayout.draw(painter, layoutRect.topLeft(), QVector<QTextLayout::FormatRange>(), layoutRect); painter->restore(); } else { d->textLayout.draw(painter, layoutRect.topLeft(), QVector<QTextLayout::FormatRange>(), layoutRect); } }
static inline void combineSize(QSizeF &result, const QSizeF &fallbackSize) { combineHints(result.rwidth(), fallbackSize.width()); combineHints(result.rheight(), fallbackSize.height()); }
void QgsMapToolAnnotation::canvasMoveEvent( QMouseEvent * e ) { QgsAnnotationItem* sItem = selectedItem(); if ( sItem && ( e->buttons() & Qt::LeftButton ) ) { if ( mCurrentMoveAction == QgsAnnotationItem::MoveMapPosition ) { sItem->setMapPosition( toMapCoordinates( e->pos() ) ); sItem->update(); } else if ( mCurrentMoveAction == QgsAnnotationItem::MoveFramePosition ) { if ( sItem->mapPositionFixed() ) { sItem->setOffsetFromReferencePoint( sItem->offsetFromReferencePoint() + ( e->posF() - mLastMousePosition ) ); } else { QPointF newCanvasPos = sItem->pos() + ( e->posF() - mLastMousePosition ); sItem->setMapPosition( toMapCoordinates( newCanvasPos.toPoint() ) ); } sItem->update(); } else if ( mCurrentMoveAction != QgsAnnotationItem::NoAction ) { //handle the frame resize actions QSizeF size = sItem->frameSize(); double xmin = sItem->offsetFromReferencePoint().x(); double ymin = sItem->offsetFromReferencePoint().y(); double xmax = xmin + size.width(); double ymax = ymin + size.height(); if ( mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRight || mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRightDown || mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRightUp ) { xmax += e->posF().x() - mLastMousePosition.x(); } if ( mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeft || mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeftDown || mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeftUp ) { xmin += e->posF().x() - mLastMousePosition.x(); } if ( mCurrentMoveAction == QgsAnnotationItem::ResizeFrameUp || mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeftUp || mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRightUp ) { ymin += e->posF().y() - mLastMousePosition.y(); } if ( mCurrentMoveAction == QgsAnnotationItem::ResizeFrameDown || mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeftDown || mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRightDown ) { ymax += e->posF().y() - mLastMousePosition.y(); } //switch min / max if necessary double tmp; if ( xmax < xmin ) { tmp = xmax; xmax = xmin; xmin = tmp; } if ( ymax < ymin ) { tmp = ymax; ymax = ymin; ymin = tmp; } sItem->setOffsetFromReferencePoint( QPointF( xmin, ymin ) ); sItem->setFrameSize( QSizeF( xmax - xmin, ymax - ymin ) ); sItem->update(); } } else if ( sItem ) { QgsAnnotationItem::MouseMoveAction moveAction = sItem->moveActionForPosition( e->posF() ); if ( mCanvas ) { mCanvas->setCursor( QCursor( sItem->cursorShapeForAction( moveAction ) ) ); } } mLastMousePosition = e->posF(); }
QPointF intervalStart(QPointF lowerBound, QSizeF interval, QPointF origin) { return QPointF(intervalStart(lowerBound.x(), interval.width(), origin.x()), intervalStart(lowerBound.y(), interval.height(), origin.y())); }
void PictureShape::paint(QPainter &painter, const KoViewConverter &converter, KoShapePaintingContext &paintContext) { Q_UNUSED(paintContext); QRectF viewRect = converter.documentToView(QRectF(QPointF(0,0), size())); if (imageData() == 0) { painter.fillRect(viewRect, QColor(Qt::gray)); return; } painter.save(); applyConversion(painter, converter); paintBorder(painter, converter); painter.restore(); QSize pixmapSize = calcOptimalPixmapSize(viewRect.size(), imageData()->image().size()); // Normalize the clipping rect if it isn't already done. m_clippingRect.normalize(imageData()->imageSize()); // Handle style:mirror, i.e. mirroring horizontally and/or vertically. // // NOTE: At this time we don't handle HorizontalOnEven // and HorizontalOnOdd, which have to know which // page they are on. In those cases we treat it as // no horizontal mirroring at all. bool doFlip = false; QSizeF shapeSize = size(); QSizeF viewSize = converter.documentToView(shapeSize); qreal midpointX = 0.0; qreal midpointY = 0.0; qreal scaleX = 1.0; qreal scaleY = 1.0; if (m_mirrorMode & MirrorHorizontal) { midpointX = viewSize.width() / qreal(2.0); scaleX = -1.0; doFlip = true; } if (m_mirrorMode & MirrorVertical) { midpointY = viewSize.height() / qreal(2.0); scaleY = -1.0; doFlip = true; } if (doFlip) { QTransform outputTransform = painter.transform(); QTransform worldTransform = QTransform(); //kDebug(31000) << "Flipping" << midpointX << midpointY << scaleX << scaleY; worldTransform.translate(midpointX, midpointY); worldTransform.scale(scaleX, scaleY); worldTransform.translate(-midpointX, -midpointY); //kDebug(31000) << "After flipping for window" << worldTransform; QTransform newTransform = worldTransform * outputTransform; painter.setWorldTransform(newTransform); } // Paint the image as prepared in waitUntilReady() if (!m_printQualityImage.isNull() && pixmapSize != m_printQualityRequestedSize) { QSizeF imageSize = m_printQualityImage.size(); QRectF cropRect( imageSize.width() * m_clippingRect.left, imageSize.height() * m_clippingRect.top, imageSize.width() * m_clippingRect.width(), imageSize.height() * m_clippingRect.height() ); painter.drawImage(viewRect, m_printQualityImage, cropRect); m_printQualityImage = QImage(); // free memory } else { QPixmap pixmap; QString key(generate_key(imageData()->key(), pixmapSize)); // If the required pixmap is not in the cache // launch a task in a background thread that scales // the source image to the required size if (!QPixmapCache::find(key, &pixmap)) { QThreadPool::globalInstance()->start(new _Private::PixmapScaler(this, pixmapSize)); painter.fillRect(viewRect, QColor(Qt::gray)); // just paint a gray rect as long as we don't have the required pixmap } else { QRectF cropRect( pixmapSize.width() * m_clippingRect.left, pixmapSize.height() * m_clippingRect.top, pixmapSize.width() * m_clippingRect.width(), pixmapSize.height() * m_clippingRect.height() ); painter.drawPixmap(viewRect, pixmap, cropRect); } } }
void Glissando::setSize(const QSizeF& s) { line = QLineF(0.0, s.height(), s.width(), 0.0); setbbox(QRectF(QPointF(), s)); }
QString PictureShape::saveStyle(KoGenStyle& style, KoShapeSavingContext& context) const { if(transparency() > 0.0) { style.addProperty("draw:image-opacity", QString("%1%").arg((1.0 - transparency()) * 100.0)); } // this attribute is need to work around a bug in LO 3.4 to make it recognice us as an // image and not just any shape. But we shouldn't produce illegal odf so: only for testing! // style.addAttribute("style:parent-style-name", "dummy"); // Mirroring if (m_mirrorMode != MirrorNone) { QString mode; if (m_mirrorMode & MirrorHorizontal) mode = "horizontal"; else if (m_mirrorMode & MirrorHorizontalOnEven) mode = "horizontal-on-even"; else if (m_mirrorMode & MirrorHorizontalOnOdd) mode = "horizontal-on-odd"; if (m_mirrorMode & MirrorVertical) { if (!mode.isEmpty()) mode += ' '; mode += "vertical"; } style.addProperty("style:mirror", mode); } switch(m_colorMode) { case Standard: style.addProperty("draw:color-mode", "standard"); break; case Greyscale: style.addProperty("draw:color-mode", "greyscale"); break; case Watermark: style.addProperty("draw:color-mode", "watermark"); break; case Mono: style.addProperty("draw:color-mode", "mono"); break; } KoImageData *imageData = qobject_cast<KoImageData*>(userData()); if (imageData != 0) { QSizeF imageSize = imageData->imageSize(); ClippingRect rect = m_clippingRect; rect.normalize(imageSize); rect.bottom = 1.0 - rect.bottom; rect.right = 1.0 - rect.right; if (!qFuzzyCompare(rect.left + rect.right + rect.top + rect.bottom, qreal(0))) { style.addProperty("fo:clip", QString("rect(%1pt, %2pt, %3pt, %4pt)") .arg(rect.top * imageSize.height()) .arg(rect.right * imageSize.width()) .arg(rect.bottom * imageSize.height()) .arg(rect.left * imageSize.width()) ); } } return KoTosContainer::saveStyle(style, context); }
void qDrawRoundedCorners(QPainter *p, qreal x1, qreal y1, qreal x2, qreal y2, const QSizeF& r1, const QSizeF& r2, Edge edge, BorderStyle s, QBrush c) { const qreal pw = (edge == TopEdge || edge == BottomEdge) ? y2-y1 : x2-x1; if (s == BorderStyle_Double) { qreal wby3 = pw/3; switch (edge) { case TopEdge: case BottomEdge: qDrawRoundedCorners(p, x1, y1, x2, y1+wby3, r1, r2, edge, BorderStyle_Solid, c); qDrawRoundedCorners(p, x1, y2-wby3, x2, y2, r1, r2, edge, BorderStyle_Solid, c); break; case LeftEdge: qDrawRoundedCorners(p, x1, y1+1, x1+wby3, y2, r1, r2, LeftEdge, BorderStyle_Solid, c); qDrawRoundedCorners(p, x2-wby3, y1+1, x2, y2, r1, r2, LeftEdge, BorderStyle_Solid, c); break; case RightEdge: qDrawRoundedCorners(p, x1, y1+1, x1+wby3, y2, r1, r2, RightEdge, BorderStyle_Solid, c); qDrawRoundedCorners(p, x2-wby3, y1+1, x2, y2, r1, r2, RightEdge, BorderStyle_Solid, c); break; default: break; } return; } else if (s == BorderStyle_Ridge || s == BorderStyle_Groove) { BorderStyle s1, s2; if (s == BorderStyle_Groove) { s1 = BorderStyle_Inset; s2 = BorderStyle_Outset; } else { s1 = BorderStyle_Outset; s2 = BorderStyle_Inset; } int pwby2 = qRound(pw/2); switch (edge) { case TopEdge: qDrawRoundedCorners(p, x1, y1, x2, y1 + pwby2, r1, r2, TopEdge, s1, c); qDrawRoundedCorners(p, x1, y1 + pwby2, x2, y2, r1, r2, TopEdge, s2, c); break; case BottomEdge: qDrawRoundedCorners(p, x1, y1 + pwby2, x2, y2, r1, r2, BottomEdge, s1, c); qDrawRoundedCorners(p, x1, y1, x2, y2-pwby2, r1, r2, BottomEdge, s2, c); break; case LeftEdge: qDrawRoundedCorners(p, x1, y1, x1 + pwby2, y2, r1, r2, LeftEdge, s1, c); qDrawRoundedCorners(p, x1 + pwby2, y1, x2, y2, r1, r2, LeftEdge, s2, c); break; case RightEdge: qDrawRoundedCorners(p, x1 + pwby2, y1, x2, y2, r1, r2, RightEdge, s1, c); qDrawRoundedCorners(p, x1, y1, x2 - pwby2, y2, r1, r2, RightEdge, s2, c); break; default: break; } } else if ((s == BorderStyle_Outset && (edge == TopEdge || edge == LeftEdge)) || (s == BorderStyle_Inset && (edge == BottomEdge || edge == RightEdge))) c = c.color().lighter(); p->save(); qreal pwby2 = pw/2; p->setBrush(Qt::NoBrush); QPen pen = qPenFromStyle(c, pw, s); pen.setCapStyle(Qt::SquareCap); // this eliminates the offby1 errors that we might hit below p->setPen(pen); switch (edge) { case TopEdge: if (!r1.isEmpty()) p->drawArc(QRectF(x1 - r1.width() + pwby2, y1 + pwby2, 2*r1.width() - pw, 2*r1.height() - pw), 135*16, -45*16); if (!r2.isEmpty()) p->drawArc(QRectF(x2 - r2.width() + pwby2, y1 + pwby2, 2*r2.width() - pw, 2*r2.height() - pw), 45*16, 45*16); break; case BottomEdge: if (!r1.isEmpty()) p->drawArc(QRectF(x1 - r1.width() + pwby2, y2 - 2*r1.height() + pwby2, 2*r1.width() - pw, 2*r1.height() - pw), -90 * 16, -45 * 16); if (!r2.isEmpty()) p->drawArc(QRectF(x2 - r2.width() + pwby2, y2 - 2*r2.height() + pwby2, 2*r2.width() - pw, 2*r2.height() - pw), -90 * 16, 45 * 16); break; case LeftEdge: if (!r1.isEmpty()) p->drawArc(QRectF(x1 + pwby2, y1 - r1.height() + pwby2, 2*r1.width() - pw, 2*r1.height() - pw), 135*16, 45*16); if (!r2.isEmpty()) p->drawArc(QRectF(x1 + pwby2, y2 - r2.height() + pwby2, 2*r2.width() - pw, 2*r2.height() - pw), 180*16, 45*16); break; case RightEdge: if (!r1.isEmpty()) p->drawArc(QRectF(x2 - 2*r1.width() + pwby2, y1 - r1.height() + pwby2, 2*r1.width() - pw, 2*r1.height() - pw), 45*16, -45*16); if (!r2.isEmpty()) p->drawArc(QRectF(x2 - 2*r2.width() + pwby2, y2 - r2.height() + pwby2, 2*r2.width() - pw, 2*r2.height() - pw), 315*16, 45*16); break; default: break; } p->restore(); }
void paintValueTracker( PaintContext* ctx, const ValueTrackerAttributes& vt, const QPointF& at ) { CartesianCoordinatePlane* plane = qobject_cast<CartesianCoordinatePlane*>( ctx->coordinatePlane() ); if ( !plane ) return; DataDimensionsList gridDimensions = ctx->coordinatePlane()->gridDimensionsList(); const QPointF bottomLeft( ctx->coordinatePlane()->translate( QPointF( plane->isHorizontalRangeReversed() ? gridDimensions.at( 0 ).end : gridDimensions.at( 0 ).start, plane->isVerticalRangeReversed() ? gridDimensions.at( 1 ).end : gridDimensions.at( 1 ).start ) ) ); const QPointF topRight( ctx->coordinatePlane()->translate( QPointF( plane->isHorizontalRangeReversed() ? gridDimensions.at( 0 ).start : gridDimensions.at( 0 ).end, plane->isVerticalRangeReversed() ? gridDimensions.at( 1 ).start : gridDimensions.at( 1 ).end ) ) ); const QPointF markerPoint = at; QPointF startPoint; if ( vt.orientations() & Qt::Horizontal ) { startPoint = QPointF( bottomLeft.x(), at.y() ); } else { startPoint = QPointF( at.x(), topRight.y() ); } QPointF endPoint; if ( vt.orientations() & Qt::Vertical ) { endPoint = QPointF( at.x(), bottomLeft.y() ); } else { endPoint = QPointF( topRight.x(), at.y() ); } const QSizeF markerSize = vt.markerSize(); const QRectF ellipseMarker = QRectF( at.x() - markerSize.width() / 2, at.y() - markerSize.height() / 2, markerSize.width(), markerSize.height() ); QPointF startMarker[3]; if ( vt.orientations() & Qt::Horizontal ) { startMarker[0] = startPoint + QPointF( 0, markerSize.height() / 2 ); startMarker[1] = startPoint + QPointF( markerSize.width() / 2, 0 ); startMarker[2] = startPoint - QPointF( 0, markerSize.height() / 2 ); } else { startMarker[0] = startPoint + QPointF( 0, markerSize.height() / 2 ); startMarker[1] = startPoint + QPointF( markerSize.width() / 2, 0 ); startMarker[2] = startPoint - QPointF( markerSize.width() / 2, 0 ); } QPointF endMarker[3]; if ( vt.orientations() & Qt::Vertical ) { endMarker[0] = endPoint + QPointF( markerSize.width() / 2, 0 ); endMarker[1] = endPoint - QPointF( 0, markerSize.height() / 2 ); endMarker[2] = endPoint - QPointF( markerSize.width() / 2, 0 ); } else { endMarker[0] = endPoint + QPointF( 0, markerSize.width() / 2 ); endMarker[1] = endPoint - QPointF( 0, markerSize.height() / 2 ); endMarker[2] = endPoint - QPointF( markerSize.width() / 2, 0 ); } QPointF topLeft = startPoint; QPointF bottomRightOffset = endPoint - topLeft; QSizeF size( bottomRightOffset.x(), bottomRightOffset.y() ); QRectF area( topLeft, size ); PainterSaver painterSaver( ctx->painter() ); ctx->painter()->setPen( PrintingParameters::scalePen( vt.linePen() ) ); ctx->painter()->setBrush( QBrush() ); ctx->painter()->drawLine( markerPoint, startPoint ); ctx->painter()->drawLine( markerPoint, endPoint ); ctx->painter()->fillRect( area, vt.areaBrush() ); ctx->painter()->setPen( PrintingParameters::scalePen( vt.markerPen() ) ); ctx->painter()->setBrush( vt.markerBrush() ); ctx->painter()->drawEllipse( ellipseMarker ); ctx->painter()->setPen( PrintingParameters::scalePen( vt.arrowBrush().color() ) ); ctx->painter()->setBrush( vt.arrowBrush() ); ctx->painter()->drawPolygon( startMarker, 3 ); ctx->painter()->drawPolygon( endMarker, 3 ); }
void SimpleRootAreaProvider::doPostLayout(KoTextLayoutRootArea *rootArea, bool isNewRootArea) { Q_UNUSED(isNewRootArea); m_textShape->update(m_textShape->outlineRect()); QSizeF newSize = m_textShape->size() - QSizeF(m_textShapeData->leftPadding() + m_textShapeData->rightPadding(), m_textShapeData->topPadding() + m_textShapeData->bottomPadding()); KoBorder *border = m_textShape->border(); if (border) { newSize -= QSizeF(border->borderWidth(KoBorder::LeftBorder) + border->borderWidth(KoBorder::RightBorder), border->borderWidth(KoBorder::TopBorder) + border->borderWidth(KoBorder::BottomBorder)); } if (m_textShapeData->verticalAlignment() & Qt::AlignBottom) { } if (m_textShapeData->verticalAlignment() & Qt::AlignVCenter) { } if (m_textShapeData->resizeMethod() == KoTextShapeData::AutoGrowWidthAndHeight ||m_textShapeData->resizeMethod() == KoTextShapeData::AutoGrowHeight) { qreal height = rootArea->bottom() - rootArea->top(); if (height > newSize.height()) { newSize.setHeight(height); } } if (m_textShapeData->resizeMethod() == KoTextShapeData::AutoGrowWidthAndHeight ||m_textShapeData->resizeMethod() == KoTextShapeData::AutoGrowWidth) { qreal width = rootArea->right() - rootArea->left(); if (width > newSize.width()) { newSize.setWidth(rootArea->right() - rootArea->left()); } } qreal newBottom = rootArea->top() + newSize.height(); KoFlake::Position sizeAnchor= KoFlake::TopLeftCorner; if (m_textShapeData->verticalAlignment() & Qt::AlignBottom) { if (true /*FIXME test no page based shapes interfering*/) { rootArea->setVerticalAlignOffset(newBottom - rootArea->bottom()); sizeAnchor= KoFlake::BottomLeftCorner; } } if (m_textShapeData->verticalAlignment() & Qt::AlignVCenter) { if (true /*FIXME test no page based shapes interfering*/) { rootArea->setVerticalAlignOffset((newBottom - rootArea->bottom()) / 2); sizeAnchor = KoFlake::CenteredPosition; } } newSize += QSizeF(m_textShapeData->leftPadding() + m_textShapeData->rightPadding(), m_textShapeData->topPadding() + m_textShapeData->bottomPadding()); if (border) { newSize += QSizeF(border->borderWidth(KoBorder::LeftBorder) + border->borderWidth(KoBorder::RightBorder), border->borderWidth(KoBorder::TopBorder) + border->borderWidth(KoBorder::BottomBorder)); } if (newSize != m_textShape->size()) { // OO grows to both sides so when to small the initial layouting needs // to keep that into account. if (m_fixAutogrow) { m_fixAutogrow = false; QSizeF tmpSize = m_textShape->size(); tmpSize.setWidth(newSize.width()); QPointF centerpos = rootArea->associatedShape()->absolutePosition(KoFlake::CenteredPosition); m_textShape->setSize(tmpSize); m_textShape->setAbsolutePosition(centerpos, KoFlake::CenteredPosition); centerpos = rootArea->associatedShape()->absolutePosition(sizeAnchor); m_textShape->setSize(newSize); m_textShape->setAbsolutePosition(centerpos, sizeAnchor); } m_textShape->setSize(newSize); } m_textShape->update(m_textShape->outlineRect()); }
/*! Render a plot to a file Supported formats are: - pdf\n Portable Document Format PDF - ps\n Postcript - svg\n Scalable Vector Graphics SVG - all image formats supported by Qt\n see QImageWriter::supportedImageFormats() Scalable vector graphic formats like PDF or SVG are superior to raster graphics formats. \param plot Plot widget \param fileName Path of the file, where the document will be stored \param format Format for the document \param sizeMM Size for the document in millimeters. \param resolution Resolution in dots per Inch (dpi) \sa renderTo(), render(), QwtPainter::setRoundingAlignment() */ void QwtPlotRenderer::renderDocument( QwtPlot *plot, const QString &fileName, const QString &format, const QSizeF &sizeMM, int resolution ) { if ( plot == NULL || sizeMM.isEmpty() || resolution <= 0 ) return; QString title = plot->title().text(); if ( title.isEmpty() ) title = "Plot Document"; const double mmToInch = 1.0 / 25.4; const QSizeF size = sizeMM * mmToInch * resolution; const QRectF documentRect( 0.0, 0.0, size.width(), size.height() ); const QString fmt = format.toLower(); if ( fmt == "pdf" ) { #ifndef QT_NO_PRINTER QPrinter printer; printer.setColorMode( QPrinter::Color ); printer.setFullPage( true ); printer.setPaperSize( sizeMM, QPrinter::Millimeter ); printer.setDocName( title ); printer.setOutputFileName( fileName ); printer.setOutputFormat( QPrinter::PdfFormat ); printer.setResolution( resolution ); QPainter painter( &printer ); render( plot, &painter, documentRect ); #endif } else if ( fmt == "ps" ) { #if QT_VERSION < 0x050000 #ifndef QT_NO_PRINTER QPrinter printer; printer.setColorMode( QPrinter::Color ); printer.setFullPage( true ); printer.setPaperSize( sizeMM, QPrinter::Millimeter ); printer.setDocName( title ); printer.setOutputFileName( fileName ); printer.setOutputFormat( QPrinter::PostScriptFormat ); printer.setResolution( resolution ); QPainter painter( &printer ); render( plot, &painter, documentRect ); #endif #endif } else if ( fmt == "svg" ) { #ifndef QWT_NO_SVG #ifdef QT_SVG_LIB #if QT_VERSION >= 0x040500 QSvgGenerator generator; generator.setTitle( title ); generator.setFileName( fileName ); generator.setResolution( resolution ); generator.setViewBox( documentRect ); QPainter painter( &generator ); render( plot, &painter, documentRect ); #endif #endif #endif } else { if ( QImageWriter::supportedImageFormats().indexOf( format.toLatin1() ) >= 0 ) { const QRect imageRect = documentRect.toRect(); const int dotsPerMeter = qRound( resolution * mmToInch * 1000.0 ); QImage image( imageRect.size(), QImage::Format_ARGB32 ); image.setDotsPerMeterX( dotsPerMeter ); image.setDotsPerMeterY( dotsPerMeter ); image.fill( QColor( Qt::white ).rgb() ); QPainter painter( &image ); render( plot, &painter, imageRect ); painter.end(); image.save( fileName, format.toLatin1() ); } } }
CLIP_EIGEN_STACK_ALIGN void ResolutionCalculator::slotCalcResolution() { // Load all rulers with a valid length in list QList<RulerData> rulerWithLengthData; QSizeF s = image->data()->getTransformedSizeData(ImageDataStore::PixelSize); for (int n=0; n<rulers.size(); n++) { bool ok; double l = rulers.at(n)->data(0).toDouble(&ok); if (ok && (l>0.0)) { RulerItem* r = dynamic_cast<RulerItem*>(rulers.at(n)); RulerData d; d.l = l; d.dx = (r->getStart().x()-r->getEnd().x())*s.width(); d.dy = (r->getStart().y()-r->getEnd().y())*s.height(); rulerWithLengthData.append(d); } } int dimension = resolutionsLocked ? 1 : 2; Eigen::Vector2d r; bool solutionOK = false; // If more amount of data is sufficient for problem, do cal if (rulerWithLengthData.size()>=dimension) { // Build linear set of equations M*x =b Eigen::MatrixXd M(rulerWithLengthData.size(), dimension); Eigen::VectorXd b(rulerWithLengthData.size()); for (int n=0; n<rulerWithLengthData.size(); n++) { RulerData d = rulerWithLengthData.at(n); if (resolutionsLocked) { // if one resolution then (x_n^2+y_n^2)*r = l_n^2 -> M(n, 0) = x_n^2+y_n^2 M(n, 0) = d.dx*d.dx+d.dy*d.dy; } else { // if two resolutions then r_1*x_n^2 + r2*y_n^2 = l_n^2 -> M(n,0) = x_n^2 ; M(n,1) = y_n^2 M(n, 0) = d.dx*d.dx; M(n, 1) = d.dy*d.dy; } b(n) = d.l*d.l; } // Solve this system via SVD -> least square solution Eigen::JacobiSVD<Eigen::MatrixXd> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV); Eigen::VectorXd x = svd.solve(b); if (resolutionsLocked) { solutionOK = x(0)>0.0; r(0) = r(1) = x(0); } else { solutionOK = (x(0)>0.0) && (x(1)>0.0) && (svd.singularValues()(1)/svd.singularValues()(0)>1e-4); r=x; } } if (solutionOK) { hRes = sqrt(r(0)); vRes = sqrt(r(1)); ui->HResDisplay->setText(QString::number(1.0/hRes, 'f', 2)); ui->VResDisplay->setText(QString::number(1.0/vRes, 'f', 2)); ui->HSizeDisplay->setText(QString::number(s.width()*hRes, 'f', 2)); ui->VSizeDisplay->setText(QString::number(s.height()*vRes, 'f', 2)); } else { ui->HResDisplay->setText(""); ui->VResDisplay->setText(""); ui->HSizeDisplay->setText(""); ui->VSizeDisplay->setText(""); hRes = -1; vRes = -1; } model->setResolution(hRes, vRes); }
QRectF CartesianChartLayout::calculateAxisGeometry(const QRectF &geometry, const QList<ChartAxisElement *> &axes) const { QSizeF left(0,0); QSizeF minLeft(0,0); QSizeF right(0,0); QSizeF minRight(0,0); QSizeF bottom(0,0); QSizeF minBottom(0,0); QSizeF top(0,0); QSizeF minTop(0,0); QSizeF labelExtents(0,0); int leftCount = 0; int rightCount = 0; int topCount = 0; int bottomCount = 0; foreach (ChartAxisElement *axis , axes) { if (!axis->isVisible()) continue; QSizeF size = axis->effectiveSizeHint(Qt::PreferredSize); //this is used to get single thick font size QSizeF minSize = axis->effectiveSizeHint(Qt::MinimumSize); switch (axis->axis()->alignment()) { case Qt::AlignLeft: left.setWidth(left.width()+size.width()); left.setHeight(qMax(left.height(),size.height())); minLeft.setWidth(minLeft.width()+minSize.width()); minLeft.setHeight(qMax(minLeft.height(),minSize.height())); labelExtents.setHeight(qMax(size.height(), labelExtents.height())); leftCount++; break; case Qt::AlignRight: right.setWidth(right.width()+size.width()); right.setHeight(qMax(right.height(),size.height())); minRight.setWidth(minRight.width()+minSize.width()); minRight.setHeight(qMax(minRight.height(),minSize.height())); labelExtents.setHeight(qMax(size.height(), labelExtents.height())); rightCount++; break; case Qt::AlignTop: top.setWidth(qMax(top.width(),size.width())); top.setHeight(top.height()+size.height()); minTop.setWidth(qMax(minTop.width(),minSize.width())); minTop.setHeight(minTop.height()+minSize.height()); labelExtents.setWidth(qMax(size.width(), labelExtents.width())); topCount++; break; case Qt::AlignBottom: bottom.setWidth(qMax(bottom.width(), size.width())); bottom.setHeight(bottom.height() + size.height()); minBottom.setWidth(qMax(minBottom.width(),minSize.width())); minBottom.setHeight(minBottom.height() + minSize.height()); labelExtents.setWidth(qMax(size.width(), labelExtents.width())); bottomCount++; break; default: qWarning()<<"Axis is without alignment !"; break; } } qreal totalVerticalAxes = leftCount + rightCount; qreal leftSqueezeRatio = 1.0; qreal rightSqueezeRatio = 1.0; qreal vratio = 0; if (totalVerticalAxes > 0) vratio = (maxAxisPortion * geometry.width()) / totalVerticalAxes; if (leftCount > 0) { int maxWidth = vratio * leftCount; if (left.width() > maxWidth) { leftSqueezeRatio = maxWidth / left.width(); left.setWidth(maxWidth); } } if (rightCount > 0) { int maxWidth = vratio * rightCount; if (right.width() > maxWidth) { rightSqueezeRatio = maxWidth / right.width(); right.setWidth(maxWidth); } } qreal totalHorizontalAxes = topCount + bottomCount; qreal topSqueezeRatio = 1.0; qreal bottomSqueezeRatio = 1.0; qreal hratio = 0; if (totalHorizontalAxes > 0) hratio = (maxAxisPortion * geometry.height()) / totalHorizontalAxes; if (topCount > 0) { int maxHeight = hratio * topCount; if (top.height() > maxHeight) { topSqueezeRatio = maxHeight / top.height(); top.setHeight(maxHeight); } } if (bottomCount > 0) { int maxHeight = hratio * bottomCount; if (bottom.height() > maxHeight) { bottomSqueezeRatio = maxHeight / bottom.height(); bottom.setHeight(maxHeight); } } qreal minHeight = qMax(minLeft.height(),minRight.height()) + 1; qreal minWidth = qMax(minTop.width(),minBottom.width()) + 1; // Ensure that there is enough space for first and last tick labels. left.setWidth(qMax(labelExtents.width(), left.width())); right.setWidth(qMax(labelExtents.width(), right.width())); top.setHeight(qMax(labelExtents.height(), top.height())); bottom.setHeight(qMax(labelExtents.height(), bottom.height())); QRectF chartRect = geometry.adjusted(qMax(left.width(),minWidth/2), qMax(top.height(), minHeight/2),-qMax(right.width(),minWidth/2),-qMax(bottom.height(),minHeight/2)); qreal leftOffset = 0; qreal rightOffset = 0; qreal topOffset = 0; qreal bottomOffset = 0; foreach (ChartAxisElement *axis , axes) { if (!axis->isVisible()) continue; QSizeF size = axis->effectiveSizeHint(Qt::PreferredSize); switch (axis->axis()->alignment()){ case Qt::AlignLeft:{ qreal width = size.width(); if (leftSqueezeRatio < 1.0) width *= leftSqueezeRatio; leftOffset+=width; axis->setGeometry(QRect(chartRect.left()-leftOffset, geometry.top(),width, geometry.bottom()),chartRect); break; } case Qt::AlignRight:{ qreal width = size.width(); if (rightSqueezeRatio < 1.0) width *= rightSqueezeRatio; axis->setGeometry(QRect(chartRect.right()+rightOffset,geometry.top(),width,geometry.bottom()),chartRect); rightOffset+=width; break; } case Qt::AlignTop: { qreal height = size.height(); if (topSqueezeRatio < 1.0) height *= topSqueezeRatio; axis->setGeometry(QRect(geometry.left(), chartRect.top() - topOffset - height, geometry.width(), height), chartRect); topOffset += height; break; } case Qt::AlignBottom: qreal height = size.height(); if (bottomSqueezeRatio < 1.0) height *= bottomSqueezeRatio; axis->setGeometry(QRect(geometry.left(), chartRect.bottom() + bottomOffset, geometry.width(), height), chartRect); bottomOffset += height; break; } } return chartRect; }
void UBGraphicsTextItem::documentSizeChanged(const QSizeF & newSize) { resize(newSize.width(), newSize.height()); }
QRectF NaZStackWidget::rectangle_around(const QPointF &p, const QSizeF &size) { QRectF rect(p, size); rect.translate(-size.width()/2, -size.height()/2); return rect; }