bool loadThemeFromBlob(const QString &themeBlob, QHash<QString, QPicture> &partPictures, QHash<QPair<QString, int>, QColor> &colors) { QFile blob(themeBlob); if (!blob.open(QIODevice::ReadOnly)) { qWarning() << __FUNCTION__ << ": Could not read blob: " << themeBlob; return false; } QDataStream blobIn(&blob); quint32 version; blobIn >> version; if (version != blobVersion) { qWarning() << __FUNCTION__ << ": Invalid blob version: " << version << " ...expected: " << blobVersion; return false; } QByteArray data; blobIn >> data; data = qUncompress(data); QBuffer dataBuffer(&data); dataBuffer.open(QIODevice::ReadOnly); QDataStream dataIn(&dataBuffer); int colorsCount; dataIn >> colorsCount; for (int i = 0; i < colorsCount; ++i) { QPair<QString, int> key; dataIn >> key; QColor value; dataIn >> value; colors.insert(key, value); } int picturesCount; dataIn >> picturesCount; for (int i = 0; i < picturesCount; ++i) { QString key; dataIn >> key; QPicture value; dataIn >> value; value.setBoundingRect(QRect(0, 0, pictureSize, pictureSize)); // Bug? The forced bounding rect was not deserialized. partPictures.insert(key, value); } if (dataIn.status() != QDataStream::Ok) { qWarning() << __FUNCTION__ << ": Invalid data blob: " << themeBlob; return false; } return true; }
QPixmap QS60StylePrivate::part(QS60StyleEnums::SkinParts part, const QSize &size, QPainter *painter, QS60StylePrivate::SkinElementFlags flags) { Q_UNUSED(painter); const QString partKey = QS60Style::partKeys().at(part); const QPicture partPicture = QS60StyleModeSpecifics::m_partPictures.value(partKey); QSize partSize(partPicture.boundingRect().size()); if (flags & (SF_PointEast | SF_PointWest)) { const int temp = partSize.width(); partSize.setWidth(partSize.height()); partSize.setHeight(temp); } const qreal scaleX = size.width() / (qreal)partSize.width(); const qreal scaleY = size.height() / (qreal)partSize.height(); QImage partImage(size, QImage::Format_ARGB32); partImage.fill(Qt::transparent); QPainter resultPainter(&partImage); QTransform t; if (flags & SF_PointEast) t.translate(size.width(), 0); else if (flags & SF_PointSouth) t.translate(size.width(), size.height()); else if (flags & SF_PointWest) t.translate(0, size.height()); t.scale(scaleX, scaleY); if (flags & SF_PointEast) t.rotate(90); else if (flags & SF_PointSouth) t.rotate(180); else if (flags & SF_PointWest) t.rotate(270); resultPainter.setTransform(t, true); const_cast<QPicture *>(&partPicture)->play(&resultPainter); resultPainter.end(); QPixmap result = QPixmap::fromImage(partImage); if (flags & SF_StateDisabled) { QStyleOption opt; QPalette *themePalette = QS60StylePrivate::themePalette(); if (themePalette) opt.palette = *themePalette; result = QApplication::style()->generatedIconPixmap(QIcon::Disabled, result, &opt); } return result; }
bool QGraph::toImage(QString path){ if(!path.isEmpty() && path.endsWith(".svg")) { QPicture pic; QPainter p; pintafunc(&pic); pic.save(path, "svg"); } else if(!path.isEmpty() && path.endsWith(".png")) { front.save(path, "PNG"); } else return false; return true; }
bool QPreviewPaintEngine::begin(QPaintDevice *) { Q_D(QPreviewPaintEngine); qDeleteAll(d->pages); d->pages.clear(); QPicture *page = new QPicture; page->d_func()->in_memory_only = true; d->painter = new QPainter(page); d->engine = d->painter->paintEngine(); d->pages.append(page); d->state = QPrinter::Active; return true; }
void ensureSerializesCorrectly(const QPicture &picture, QDataStream::Version version) { QDataStream stream; QBuffer buffer; buffer.open(QIODevice::WriteOnly); stream.setDevice(&buffer); stream.setVersion(version); stream << picture; buffer.close(); buffer.open(QIODevice::ReadOnly); QPicture readpicture; stream >> readpicture; QVERIFY2(memcmp(picture.data(), readpicture.data(), picture.size()) == 0, qPrintable(QString::fromLatin1("Picture data does not compare equal for QDataStream version %1").arg(version))); }
/** Draws the section base objects to the specified painter & x/y offsets */ void MReportSection::drawHeaderObjects( FLStylePainter *p, MPageCollection *pages, MReportSection * header ) { MCalcObject * calcfield; // Set the offsets int xcalc = header->getLastXOffset(); int ycalc = header->getLastYOffset(); QPicture * currentPage = ( QPicture * ) p->painter()->device(); QPicture * lastPage = header->onPage(); QPicture * currentPageCopy = 0; QPicture * lastPageCopy = 0; if ( currentPage != lastPage ) { p->painter()->end(); currentPageCopy = new QPicture( *currentPage ); lastPageCopy = new QPicture( *lastPage ); p->painter()->begin( lastPage ); lastPageCopy->play( p->painter() ); } QObject::setName( QString( "_##H%1-%2" ).arg( strIdSec_ ).arg( level ) ); p->beginSection( xcalc, ycalc, width, height, this ); uint countObj = 0; // Draw the calculated field collection for ( calcfield = calculatedFields.first(); calcfield != 0; calcfield = calculatedFields.next() ) { if ( calcfield->getDrawAtHeader() ) { calcfield->QObject::setName( QString( "_##H%1-Calc.%2-%3" ).arg( idSec_ ).arg( calcfield->fieldName ).arg( countObj++ ) ); p->beginMark( calcfield->getX(), calcfield->getY(), calcfield ); calcfield->draw( p ); p->endMark(); } } p->endSection(); if ( currentPage != lastPage ) { p->painter()->end(); p->painter()->begin( currentPage ); currentPageCopy->play( p->painter() ); delete lastPageCopy; delete currentPageCopy; } }
void CollaborativeDrawingWidget::commitDrawing(QPicture drawingPictureData) { qWarning() << "commitDrawing size" << drawingPictureData.size(); BaseDrawingWidget::commitDrawing(drawingPictureData); emit drawingCommited(m_currentSession, drawingPictureData); }
void PictureRenderer::render(QPainter *painter, const QRectF &bounds) { QRect br = picture.boundingRect(); QTransform worldTransform = painter->worldTransform(); painter->translate(bounds.topLeft()); painter->scale(bounds.width()/br.width(), bounds.height()/br.height()); painter->drawPicture(br.topLeft(), picture); painter->setWorldTransform(worldTransform); }
void BaseDrawingWidget::commitDrawing(QPicture drawingPictureData) { getDrawingData()->registerAction(drawingPictureData); getDrawingData()->setModified(true); // update the stage getDrawingData()->update(drawingPictureData.boundingRect().adjusted(-drawingPen.width()-5, -drawingPen.width()-5, drawingPen.width()+5, drawingPen.width()+5)); }
void CollaborativeDrawingWidget::drawingArrived(QString sessionName, QByteArray picData, bool isInitialState) { // this slot will be invoked when the user joins a new session and the server // sends the current drawing state for this session QPicture pic; qWarning() << "Session state data of size : " << picData.size() << "from session" << sessionName; if(isInitialState) { // set the session name m_currentSession = sessionName; // clear up any old data getDrawingData()->clear(); // the widget should be enabled now setEnabled(true); } pic.setData(picData.constData(), picData.size()); // commit the new data BaseDrawingWidget::commitDrawing(pic); }
void QgsSvgCache::cachePicture( QgsSvgCacheEntry *entry, bool forceVectorOutput ) { if ( !entry ) { return; } delete entry->picture; entry->picture = 0; //correct QPictures dpi correction QPicture* picture = new QPicture(); QRectF rect; QSvgRenderer r( entry->svgContent ); double hwRatio = 1.0; if ( r.viewBoxF().width() > 0 ) { hwRatio = r.viewBoxF().height() / r.viewBoxF().width(); } bool drawOnScreen = qgsDoubleNear( entry->rasterScaleFactor, 1.0, 0.1 ); if ( drawOnScreen && forceVectorOutput ) //forceVectorOutput always true in case of composer draw / composer preview { // fix to ensure rotated symbols scale with composer page (i.e. not map item) zoom double wSize = entry->size; double hSize = wSize * hwRatio; QSizeF s( r.viewBoxF().size() ); s.scale( wSize, hSize, Qt::KeepAspectRatio ); rect = QRectF( -s.width() / 2.0, -s.height() / 2.0, s.width(), s.height() ); } else { // output for print or image saving @ specific dpi double scaledSize = entry->size / 25.4 / ( entry->rasterScaleFactor * entry->widthScaleFactor ); double wSize = scaledSize * picture->logicalDpiX(); double hSize = scaledSize * picture->logicalDpiY() * r.viewBoxF().height() / r.viewBoxF().width(); rect = QRectF( QPointF( -wSize / 2.0, -hSize / 2.0 ), QSizeF( wSize, hSize ) ); } QPainter p( picture ); r.render( &p, rect ); entry->picture = picture; mTotalSize += entry->picture->size(); }
void tst_QPicture::serialization() { QDataStream stream; const int thisVersion = stream.version(); for (int version = QDataStream::Qt_1_0; version <= thisVersion; ++version) { const QDataStream::Version versionEnum = static_cast<QDataStream::Version>(version); { // streaming of null pictures ensureSerializesCorrectly(QPicture(), versionEnum); } { // picture with a simple line, checking bitwise equality QPicture picture; QPainter painter(&picture); painter.drawLine(10, 20, 30, 40); ensureSerializesCorrectly(picture, versionEnum); } } { // Test features that were added after Qt 4.5, as that was hard-coded as the major // version for a while, which was incorrect. In this case, we'll test font hints. QPicture picture; QPainter painter; QFont font; font.setStyleName("Blah"); font.setHintingPreference(QFont::PreferFullHinting); painter.begin(&picture); painter.setFont(font); painter.drawText(20, 20, "Hello"); painter.end(); Picture customPicture; painter.begin(&customPicture); picture.play(&painter); const QFont actualFont = ((PaintEngine*)customPicture.paintEngine())->font(); painter.end(); QCOMPARE(actualFont.styleName(), QStringLiteral("Blah")); QCOMPARE(actualFont.hintingPreference(), QFont::PreferFullHinting); } }
void PictureDisplay::keyPressEvent( QKeyEvent *k ) { switch ( tolower(k->ascii()) ) { case 'r': // reload pict->load( name ); update(); break; case 'q': // quit QApplication::exit(); break; } }
void FLReportViewer::saveSVGStyle() { if (report) { QString fileName = QFileDialog::getSaveFileName("", tr("Fichero SVG (*.svg)"), this, tr("Guardar en SVG"), tr("Guardar en SVG")); if (fileName.isEmpty()) return; if (!fileName.upper().contains(".SVG")) fileName += ".svg"; if (QFile::exists(fileName) && QMessageBox::question(this, tr("Sobreescribir %1").arg(fileName), tr("Ya existe un fichero llamado %1. ¿ Desea sobreescribirlo ?").arg(fileName), tr("&Sí"), tr("&No"), QString::null, 0, 1)) return; FLStylePainter::setSVGMode(true); updateReport(); FLStylePainter::setSVGMode(false); QStringList fileNames; QString fname; QPicture *page; QSize psize; for (int i = 0; i < report->pageCount(); ++i) { fname = fileName + QString::number(i); fileNames.append(fname); page = report->getPageAt(i); psize = report->pageDimensions(); page->setBoundingRect(QRect(QPoint(0, 0), psize)); page->save(fname, "svg"); } FLStylePainter::normalizeSVGFile(fileName, fileNames); updateReport(); } }
QPicture QgsSvgCache::svgAsPicture( const QString &path, double size, const QColor &fill, const QColor &stroke, double strokeWidth, double widthScaleFactor, bool forceVectorOutput, double fixedAspectRatio ) { QMutexLocker locker( &mMutex ); QgsSvgCacheEntry *currentEntry = cacheEntry( path, size, fill, stroke, strokeWidth, widthScaleFactor, fixedAspectRatio ); //if current entry picture is 0: cache picture for entry //update stats for memory usage if ( !currentEntry->picture ) { cachePicture( currentEntry, forceVectorOutput ); trimToMaximumSize(); } QPicture p; // For some reason p.detach() doesn't seem to always work as intended, at // least with QT 5.5 on Ubuntu 16.04 // Serialization/deserialization is a safe way to be ensured we don't // share a copy. p.setData( currentEntry->picture->data(), currentEntry->picture->size() ); return p; }
bool MReportViewer::printPosReport() { if (report == 0) return false; posprinter = new FLPosPrinter(); posprinter->setPaperWidth((FLPosPrinter::PaperWidth) report->pageSize()); posprinter->setPrinterName(printerName_); QPicture *page; QPainter painter; bool printRev = false; int viewIdx = report->getCurrentIndex(); int printCopies = numCopies_; painter.begin(posprinter); QPaintDeviceMetrics pdm(posprinter); QSize dim(report->pageDimensions()); painter.setWindow(0, 0, dim.width(), dim.height()); painter.setViewport(0, 0, pdm.width(), pdm.height()); for (int j = 0; j < printCopies; j++) { report->setCurrentPage(1); page = report->getCurrentPage(); page->play(&painter); } painter.end(); report->setCurrentPage(viewIdx); delete posprinter; return true; }
bool QPreviewPaintEngine::newPage() { Q_D(QPreviewPaintEngine); QPicture *page = new QPicture; page->d_func()->in_memory_only = true; QPainter *tmp_painter = new QPainter(page); QPaintEngine *tmp_engine = tmp_painter->paintEngine(); // copy the painter state from the original painter Q_ASSERT(painter()->d_func()->state && tmp_painter->d_func()->state); *tmp_painter->d_func()->state = *painter()->d_func()->state; // composition modes aren't supported on a QPrinter and yields a // warning, so ignore it for now tmp_engine->setDirty(DirtyFlags(AllDirty & ~DirtyCompositionMode)); tmp_engine->syncState(); delete d->painter; d->painter = tmp_painter; d->pages.append(page); d->engine = tmp_engine; return true; }
void KoPictureClipart::drawQPicture(QPicture& clipart, QPainter& painter, int x, int y, int width, int height, int sx, int sy, int sw, int sh) { kdDebug(30003) << "Drawing KoPictureClipart " << this << endl; kdDebug(30003) << " x=" << x << " y=" << y << " width=" << width << " height=" << height << endl; kdDebug(30003) << " sx=" << sx << " sy=" << sy << " sw=" << sw << " sh=" << sh << endl; painter.save(); // Thanks to Harri, Qt3 makes it much easier than Qt2 ;) QRect br = clipart.boundingRect(); kdDebug(30003) << " Bounding rect. " << br << endl; painter.translate(x,y); // Translating must be done before scaling! if ( br.width() && br.height() ) painter.scale(double(width)/double(br.width()),double(height)/double(br.height())); else kdWarning(30003) << "Null bounding rectangle: " << br.width() << " x " << br.height() << endl; painter.drawPicture(0,0,clipart); painter.restore(); }
void DrawingData::registerAction(QPicture actions) { QRect boundingRect = actions.boundingRect().adjusted(-2,-2,2,2); // fix negative / too large coordinates if(boundingRect.x() < 0) boundingRect.setX(0); if(boundingRect.y() < 0) boundingRect.setY(0); if(boundingRect.x() > width()) boundingRect.setX(width()); if(boundingRect.y() > height()) boundingRect.setY(height()); // backup the area to be painted, to be used for undo'ing later QPixmap areaToChange = QPixmap::fromImage(stage.copy(boundingRect)); // set the properties of this drawing step for undo/redo currentAction->setActions(actions); currentAction->setPrevPixmap(areaToChange, boundingRect); // add to the undo stack undoStack.push(currentAction); currentAction = new DrawingAction(this); }
void QgsSvgCache::cachePicture( QgsSvgCacheEntry *entry ) { if ( !entry ) { return; } delete entry->picture; entry->picture = 0; //correct QPictures dpi correction QPicture* picture = new QPicture(); double pictureSize = entry->size / 25.4 / ( entry->rasterScaleFactor * entry->widthScaleFactor ) * picture->logicalDpiX(); QRectF rect( QPointF( -pictureSize / 2.0, -pictureSize / 2.0 ), QSizeF( pictureSize, pictureSize ) ); QSvgRenderer renderer( entry->svgContent ); QPainter painter( picture ); renderer.render( &painter, rect ); entry->picture = picture; mTotalSize += entry->picture->size(); }
/** Renders the report as a page collection - the caller * is responsible for de-allocating the returned * collection * * copyright : (C) 2002-2008 InfoSiAL S.L. * email : [email protected] * */ MPageCollection *MReportEngine::renderReport(int initRow, int initCol, MPageCollection *pages, uint flags) { fillRecords_ = flags & MReportEngine::FillRecords; bool pageBreak = flags & MReportEngine::PageBreak; bool append = flags & MReportEngine::Append; cancelRender = false; currRecord_ = 0; csvData_ = QString::null; p->setStyleName(styleName_); // Create the page collection QPicture *currentPage = 0; QPicture *currentPageCopy = 0; bool lastPageFound = false; if (pages == 0) { pages = new MPageCollection(this); currPage = 0; } else { if (append && !pageBreak) { currX = leftMargin ; lastPageFound = true; currentPage = pages->getLastPage(); p->painter()->end(); currentPageCopy = new QPicture(*currentPage); p->painter()->begin(currentPage); currentPageCopy->play(p->painter()); delete currentPageCopy; } } // Initialize the basic page data currHeight = pageHeight - (bottomMargin + pFooter->getHeight()); currDate = QDate::currentDate(); // Initialize the grand total array clearGrantTotals(); for (int i = 0; i < rFooter->getCalcFieldCount(); i++) grandTotal->append(new QMemArray<double>); // Create the first page if (!lastPageFound) startPage(pages); unsigned int rowCount = records.length(); if (rowCount <= 1) rowCount = 2; uint nRecord = 0; // Draw the details drawDetail(pages, 0, nRecord, initRow, initCol); // Finish the last page of the report endPage(pages); // Destroy the page painter p->painter()->end(); // Set the page collection attributes pages->setPageDimensions(QSize(pageWidth, pageHeight)); pages->setPageSize(pageSize); pages->setPageOrientation(pageOrientation); pages->setPrintToPos(printToPos); fillRecords_ = false; // Send final status emit signalRenderStatus(rowCount / 2); return pages; }
void Export::slotAccept() { switch ( group -> selectedId() ) { case 0: { QString fn = QFileDialog::getSaveFileName( "projects/output/", "PNG sequence ( *.png )", this ); if ( !fn.isEmpty() ) { if ( k_toon -> scenes() -> exportAnimation( fn, "PNG" ) > 0 ) k_toon -> statusBar() -> message( tr( "Animation Exported Successfully" ), 2000 ); else k_toon -> statusBar() -> message( tr( "Could not Export Animation" ), 2000 ); } break; } case 1: { QString fn = QFileDialog::getSaveFileName( "projects/output/", "Single PNG ( *.png )", this ); if ( !fn.isEmpty() ) { QPixmap exp; fn = fn + ".png"; exp.convertFromImage( k_toon -> renderCameraPreview() -> grabFrameBuffer() ); if ( !exp.save( fn, "PNG" ) ) k_toon -> statusBar() -> message( tr( "Could not save the file: %1" ).arg( fn ), 2000 ); } break; } case 2: { QString fn = QFileDialog::getSaveFileName( "projects/output/", "Macromedia Flash ( *.swf )", this ); if ( !fn.isEmpty() ) { int number_of_images = k_toon -> scenes() -> exportAnimation( fn, "JPEG" ); if ( number_of_images > 0 ) { int frame_rate = k_toon -> currentStatus() -> currentFrameRate(); SWFMovie *movie = doMovie( 360, 280 ); movie -> setRate( ( float )frame_rate ); QStringList images; for ( int i = 1; i < number_of_images; i++ ) { QString iterator = QString::number( i ); iterator = iterator.rightJustify( 3, '0' ); images << QString( fn + iterator + ".jpg" ); } SWFDisplayItem *frame = doAnimation( movie, images ); frame -> addColor( 255, 0, 0 ); if ( movie -> save( ( char * )( fn + ".swf" ).latin1() ) < 0 ) k_toon -> statusBar() -> message( tr( "Could not Export Animation" ), 2000 ); else k_toon -> statusBar() -> message( tr( "Animation Exported Successfully" ), 2000 ); for ( int i = 1; i < number_of_images; i++ ) { QString iterator = QString::number( i ); iterator = iterator.rightJustify( 3, '0' ); QFile::remove( fn + iterator + ".jpg" ); } } else k_toon -> statusBar() -> message( tr( "Could not Export Animation" ), 2000 ); } break; } case 3: { QString fn = QFileDialog::getSaveFileName( "projects/output/", "Scalable Vector Graphics ( *.svg )", this ); if ( !fn.isEmpty() ) { QPixmap exp; fn = fn + ".svg"; exp.convertFromImage( k_toon -> renderCameraPreview() -> grabFrameBuffer() ); QPainter painter; QPicture picture; painter.begin( &picture ); painter.drawPixmap( 0, 0, exp ); painter.end(); if ( picture.save( fn, "svg" ) ) k_toon -> statusBar() -> message( tr( "SVG Exported Successfully" ), 2000 ); else k_toon -> statusBar() -> message( tr( "Could not Export SVG" ), 2000 ); } break; } default: break; } close( true ); }
void MainWindow::on_divideButton_clicked() { cubeRow = ui->cubeRow->value(); cubeCol = ui->cubeCol->value(); if(cubeRow*cubeCol >= 4 && !filename.isEmpty() && image_origin.rows >= cubeRow*3 && image_origin.cols >= cubeCol*3) { //I. divide image //1.prepare //int largeSquare = (int)floor(sqrt(cubeNum));//get the largest square that can be made //qDebug() << "largeSquare:" <<largeSquare; float picRatio = (float)image_origin.rows / (float)image_origin.cols;//row行数col列数 //qDebug() << "picRatio:" <<picRatio; float cubeRatio = (float)cubeRow / (float)cubeCol; int scale, fixedCol, fixedRow; if(picRatio >= cubeRatio)//row long { scale = image_origin.cols/(cubeCol*3);//img size devide cube's totol col fixedRow = scale*cubeRow*3;//set the size corresponding cube's fixedCol = scale*cubeCol*3; } else//col long { scale = image_origin.rows/(cubeRow*3); fixedRow = scale*cubeRow*3; fixedCol = scale*cubeCol*3; } int removeRows = image_origin.rows - fixedRow; int removeCols = image_origin.cols - fixedCol; //qDebug()<<"scale:"<<scale<<" row:"<<fixedRow<<" col:"<<fixedCol<<" Original resolution:"<<image_origin.rows<<image_origin.cols<<" remove:"<<removeRows<<removeCols; int removeRows_top,removeRows_down,removeCols_left,removeCols_right; if(removeRows%2 != 0)//the remove num of rows is not even number { //up need remove one more than down removeRows_top = removeRows/2 + 1; removeRows_down = removeRows/2; } else removeRows_top = removeRows_down = removeRows/2; if(removeCols%2 != 0)//the remove num of cols is not even number { //left need remove one more than right removeCols_left = removeCols/2 + 1; removeCols_right = removeCols/2; } else removeCols_left = removeCols_right = removeCols/2; //qDebug()<<"removeRow_fixed:"<<removeRows_top<<removeRows_down<<"removeCol_fixed:"<<removeCols_left<<removeCols_right; cv::Mat fixedImage = image_origin(Rect(removeCols_left,removeRows_top,fixedCol,fixedRow));//改好大小的图片 //resize the image cv::Size dsize = cv::Size(cubeCol*3,cubeRow*3);//Image resolution of the match cube ratio //cv::Mat image_resize = fixedImage; cv::resize(fixedImage, image_resize, dsize); image_resize = changeRubixColor(image_resize); cv::cvtColor(image_resize, image_resize, CV_BGR2RGB); //image_resize---->this is what we want!!!! QImage QimgResize = QImage((const unsigned char*)(image_resize.data),image_resize.cols,image_resize.rows, image_resize.cols*image_resize.channels(), QImage::Format_RGB888); //qDebug() << "QimgResizeRect:" << QimgResize.rect(); ui->picLabel->clear(); imgScaled = QimgResize.scaled(ui->picLabel->size(),Qt::KeepAspectRatio); //qDebug() << "imgScaledRect:" << imgScaled.rect(); ui->picLabel->setPixmap(QPixmap::fromImage(imgScaled));//image insert into label /*--------------------------drawing grids----------------------------*/ QPicture picture; QPainter painter; QPen pen_thick,pen_thin; pen_thick.setWidth(3); pen_thick.setColor(Qt::gray); pen_thin.setWidth(1); pen_thin.setColor(Qt::gray); painter.begin(&picture); picture.setBoundingRect(imgScaled.rect()); //set the boundary of painting //draw col line painter.setPen(pen_thin); for(int i = 0; i <= cubeCol*3; i++) painter.drawLine(QLineF((float)imgScaled.rect().width()/cubeCol/3.0*i, 0, (float)imgScaled.rect().width()/cubeCol/3.0*i, imgScaled.rect().height())); painter.setPen(pen_thick); for(int i = 0; i <= cubeCol; i++) painter.drawLine(QLineF((float)imgScaled.rect().width()/cubeCol*i, 0, (float)imgScaled.rect().width()/cubeCol*i, imgScaled.rect().height())); //draw row line painter.setPen(pen_thin); for(int i = 0; i <= cubeRow*3; i++) painter.drawLine(QLineF(0, (float)imgScaled.rect().height()/cubeRow/3.0*i, imgScaled.rect().width(), (float)imgScaled.rect().height()/cubeRow/3.0*i)); painter.setPen(pen_thick); for(int i = 0; i <= cubeRow; i++) painter.drawLine(QLineF(0, (float)imgScaled.rect().height()/cubeRow*i, imgScaled.rect().width(), (float)imgScaled.rect().height()/cubeRow*i)); painter.end(); picture.save("draw_record.pic"); ui->picLabelUp->setPicture(picture); } else if(cubeRow*cubeCol < 4) { int ret = QMessageBox::warning(this, "Warning", "The number of cubes is at least four!", QMessageBox::Abort); if (ret == QMessageBox::Abort) qDebug() << "WARNING!!"; } else if(filename.isEmpty()) { int ret = QMessageBox::warning(this, "Warning", "You need choose an image file!", QMessageBox::Abort); if (ret == QMessageBox::Abort) qDebug() << "WARNING!!"; } else if(image_origin.rows < cubeRow*3 || image_origin.cols < cubeCol*3) { int ret = QMessageBox::warning(this, "Warning", "Too many cubes!", QMessageBox::Abort); if (ret == QMessageBox::Abort) qDebug() << "WARNING!!"; } }
void MainWindow::on_chooseCube_editingFinished() { ui->divideButton->clicked(); ui->picLabelRoi->clear(); int num_cube = ui->chooseCube->value(); if(num_cube > 0 && num_cube <= cubeRow * cubeCol) { //find cube in pic int num_row = (num_cube - 1) / cubeCol;//start at 0 int num_col = (num_cube - 1) % cubeCol; // start at 0 //qDebug() << "row,col:" << num_row << num_col; chooseCubeColor = image_resize(cv::Rect(num_col*3,num_row*3,3,3));//cube what we choose // //painting roi // float multiple = (float)imgScaled.width() / (float)image_resize.size().width; // QPicture picture0; // QPainter painter0; // QPen pen_roi; // pen_roi.setColor(Qt::red); // pen_roi.setWidth(2); // painter0.begin(&picture0); // painter0.setPen(pen_roi); // //painting red Roi // painter0.drawRect(QRectF(num_col*3*multiple,num_row*3*multiple,3*multiple,3*multiple)); // //qDebug() << QRectF(num_col*3*multiple,num_row*3*multiple,3*multiple,3*multiple); // painter0.end(); // picture0.save("draw_roi.pic"); // ui->picLabelRoi->setPicture(picture0); //painting cube QPicture picture; QPainter painter; QPen pen_cube; pen_cube.setColor(Qt::black); pen_cube.setWidth(2); painter.begin(&picture); painter.setPen(pen_cube); QBrush brush(Qt::SolidPattern); //painting choose cube int block_size = 40; for(int i = 0; i < 9; i++) { //qDebug() << "RGB:" << chooseCubeColor.at<Vec3b>(i/3,i%3).val[0]<<chooseCubeColor.at<Vec3b>(i/3,i%3).val[1]<<chooseCubeColor.at<Vec3b>(i/3,i%3).val[2]; brush.setColor(QColor(chooseCubeColor.at<Vec3b>(i/3,i%3).val[0],chooseCubeColor.at<Vec3b>(i/3,i%3).val[1],chooseCubeColor.at<Vec3b>(i/3,i%3).val[2]));//RGB 3 channels painter.setBrush(brush); painter.drawRoundRect(QRect(block_size*i%(block_size*3),block_size*(i/3),block_size,block_size)); } painter.end(); picture.save("draw_cube.pic"); ui->showCubeChoose->setPicture(picture); //store colors of cube for(int i = 0; i < 9; i++) { QColor qcolor = QColor(chooseCubeColor.at<Vec3b>(i/3,i%3).val[0],chooseCubeColor.at<Vec3b>(i/3,i%3).val[1],chooseCubeColor.at<Vec3b>(i/3,i%3).val[2]);//RGB 3 channels int color_num; if(qcolor == colorTable_cube[0]) color_num = 0; else if(qcolor == colorTable_cube[1]) color_num = 1; else if(qcolor == colorTable_cube[2]) color_num = 2; else if(qcolor == colorTable_cube[3]) color_num = 3; else if(qcolor == colorTable_cube[4]) color_num = 4; else if(qcolor == colorTable_cube[5]) color_num = 5; else color_num = -1; col[i] = RubikColor(color_num); //qDebug() << "color:" << color_num; } dlg.setRubikColor(col); } else { int ret = QMessageBox::warning(this, "Warning", "Please choose the cube you want to make!", QMessageBox::Abort); if (ret == QMessageBox::Abort) qDebug() << "WARNING!!"; } }
void SvgCanvas::actionExport_to_callback() { QDialog dialog; ExportToDialog export_to_dialog; export_to_dialog.setupUi(&dialog); QListWidget *list = export_to_dialog.formats_listWidget; QListWidgetItem *item; //Pixmaps formats QList<QByteArray> formats=QImageWriter::supportedImageFormats(); for(int i=0;i<formats.size();i++) { QString text(formats[i]); item=new QListWidgetItem(text,list); item->setData(1,QVariant(PIXMAP)); } //Vector formats formats= QPicture::outputFormats(); for(int i=0;i<formats.size();i++) { QString text(formats[i]); item=new QListWidgetItem(text,list); item->setData(1,QVariant(PICTURE)); } item=new QListWidgetItem("ps",list); item->setData(1,QVariant(PRINTER)); item=new QListWidgetItem("pdf",list); item->setData(1,QVariant(PDF)); item=new QListWidgetItem("svg",list); item->setData(1,QVariant(SVG)); int ok=dialog.exec(); if(ok==QDialog::Rejected) return; item =list->currentItem(); int format=item->data(1).toInt(); QPainter plot; switch(format) { case PIXMAP: { bool ok; int h, w = QInputDialog::getInteger(this, tr("Width"), tr("Width:"), 300, 0, 2147483647, 1, &ok); if(!ok) return; h=QInputDialog::getInteger(this, tr("Height"), tr("Height:"), 200, 0, 2147483647, 1, &ok); if(!ok) return; QString s = QFileDialog::getSaveFileName(this, "Choose a filename to save"); if(s.isEmpty()) return; QImage image(w,h,QImage::Format_RGB32); plot.begin(&image); svg_plot->renderer()->render(&plot); plot.end(); image.save(s,item->data(0).toString().toLocal8Bit().data()); } break; case PICTURE: { bool ok; int h, w = QInputDialog::getInteger(this, tr("Width"), tr("Width:"), 300, 0, 2147483647, 1, &ok); if(!ok) return; h=QInputDialog::getInteger(this, tr("Height"), tr("Height:"), 200, 0, 2147483647, 1, &ok); if(!ok) return; QString s = QFileDialog::getSaveFileName(this, "Choose a filename to save"); if(s.isEmpty()) return; QPicture image; const QRect r(0,0,w,h); image.setBoundingRect(r); plot.begin(&image); svg_plot->renderer()->render(&plot); plot.end(); image.save(s,item->data(0).toString().toLocal8Bit().data()); } break; case PRINTER: { QPrinter p; QPrintDialog printDialog(&p, this); if (printDialog.exec() != QDialog::Accepted) return; plot.begin(&p); svg_plot->renderer()->render(&plot); plot.end(); } break; case PDF: { QPrinter p; QPrintDialog printDialog(&p, this); p.setOutputFormat(QPrinter::PdfFormat); if (printDialog.exec() != QDialog::Accepted) return; plot.begin(&p); svg_plot->renderer()->render(&plot); plot.end(); } break; case SVG: { QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("*.svg")); QSvgGenerator p; p.setFileName(fileName); plot.begin(&p); svg_plot->renderer()->render(&plot); plot.end(); } } }
bool MReportViewer::printGhostReportToPS(const QString &outPsFile) { if (report == 0) return false; int cnt = report->pageCount(); if (cnt == 0) return false; psprinter = new PSPrinter(PSPrinter::HighResolution); psprinter->setPageSize((PSPrinter::PageSize) report->pageSize()); if ((PSPrinter::PageSize) report->pageSize() == PSPrinter::Custom) psprinter->setCustomPaperSize(report->pageDimensions()); psprinter->setOrientation((PSPrinter::Orientation) report->pageOrientation()); psprinter->setMinMax(1, cnt); psprinter->setFromTo(1, cnt); psprinter->setFullPage(true); psprinter->setColorMode((PSPrinter::ColorMode) colorMode_); psprinter->setNumCopies(numCopies_); psprinter->setResolution(dpi_); QPicture *page; QPainter painter; bool printRev = false; int viewIdx = report->getCurrentIndex(); if (psprinter->pageOrder() == QPrinter::LastPageFirst) printRev = true; int printFrom = psprinter->fromPage() - 1; int printTo = psprinter->toPage(); int printCnt = (printTo - printFrom); int printCopies = psprinter->numCopies(); int totalSteps = printCnt * printCopies; int currentStep = 1; psprinter->setNumCopies(1); psprinter->setOutputToFile(true); psprinter->setOutputFileName(outPsFile); QProgressDialog progress(tr("Imprimiendo Informe..."), tr("Cancelar"), totalSteps, this, tr("progreso"), true); progress.setMinimumDuration(M_PROGRESS_DELAY); QObject::connect(&progress, SIGNAL(cancelled()), this, SLOT(slotCancelPrinting())); progress.setProgress(0); qApp->processEvents(); painter.begin(psprinter); QPaintDeviceMetrics pdm(psprinter); QSize dim(report->pageDimensions()); painter.setWindow(0, 0, dim.width(), dim.height()); painter.setViewport(0, 0, pdm.width(), pdm.height()); for (int j = 0; j < printCopies; j++) { for (int i = printFrom; i < printTo; i++, currentStep++) { if (!psprinter->aborted()) { progress.setProgress(currentStep); qApp->processEvents(); if (printRev) report->setCurrentPage((printCnt == 1) ? i : (printCnt - 1) - i); else report->setCurrentPage(i); page = report->getCurrentPage(); page->play(&painter); if ((i - printFrom) < printCnt - 1) psprinter->newPage(); } else { j = printCopies; break; } } if (j < printCopies - 1) psprinter->newPage(); } painter.end(); report->setCurrentPage(viewIdx); delete psprinter; return true; }
/** Imprime directamente sobre formato PS */ bool MReportViewer::printReportToPS(const QString &outPsFile) { // Check for a report if (report == 0) return false; #if defined(Q_OS_WIN32) || defined(Q_OS_MACX) return printGhostReportToPS(outPsFile); #endif // Get the page count int cnt = report->pageCount(); // Check if there is a report or any pages to print if (cnt == 0) { QMessageBox::critical(this, "Kugar", tr("No hay páginas en el\ninforme para."), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); return false; } // Set the printer dialog printer = new QPrinter(QPrinter::HighResolution); printer->setPageSize((QPrinter::PageSize) report->pageSize()); if ((QPrinter::PageSize) report->pageSize() == QPrinter::Custom) printer->setCustomPaperSize(report->pageDimensions()); printer->setOrientation((QPrinter::Orientation) report->pageOrientation()); printer->setMinMax(1, cnt); printer->setFromTo(1, cnt); printer->setFullPage(true); printer->setColorMode((QPrinter::ColorMode) colorMode_); printer->setNumCopies(numCopies_); printer->setOutputToFile(true); printer->setOutputFileName(outPsFile); QPicture *page; QPainter painter; bool printRev = false; // Save the viewer's page index int viewIdx = report->getCurrentIndex(); // Check the order we are printing the pages if (printer->pageOrder() == QPrinter::LastPageFirst) printRev = true; // Get the count of pages and copies to print int printFrom = printer->fromPage() - 1; int printTo = printer->toPage(); int printCnt = (printTo - printFrom); int printCopies = printer->numCopies(); int totalSteps = printCnt * printCopies; int currentStep = 1; // Set copies to 1, QPrinter copies does not appear to work ... printer->setNumCopies(numCopies_); printer->setResolution(dpi_); // Setup the progress dialog QProgressDialog progress(tr("Imprimiendo Informe..."), tr("Cancelar"), totalSteps, this, tr("progreso"), true); progress.setMinimumDuration(M_PROGRESS_DELAY); QObject::connect(&progress, SIGNAL(cancelled()), this, SLOT(slotCancelPrinting())); progress.setProgress(0); qApp->processEvents(); // Start the printer painter.begin(printer); QPaintDeviceMetrics pdm(printer); QSize dim(report->pageDimensions()); painter.setWindow(0, 0, dim.width(), dim.height()); painter.setViewport(0, 0, pdm.width(), pdm.height()); // Print each page in the collection for (int j = 0; j < printCopies; j++) { for (int i = printFrom; i < printTo; i++, currentStep++) { if (!printer->aborted()) { progress.setProgress(currentStep); qApp->processEvents(); if (printRev) report->setCurrentPage((printCnt == 1) ? i : (printCnt - 1) - i); else report->setCurrentPage(i); page = report->getCurrentPage(); page->play(&painter); if ((i - printFrom) < printCnt - 1) printer->newPage(); } else { j = printCopies; break; } } if (j < printCopies - 1) printer->newPage(); } // Cleanup printing painter.end(); report->setCurrentPage(viewIdx); delete printer; return true; }
/** Prints the rendered report to the selected printer - displays Qt print dialog */ bool MReportViewer::printReport() { // Check for a report if (report == 0) return false; report->setPrintToPos(printToPos_); if (report->printToPos()) return printPosReport(); #if defined(Q_OS_WIN32) bool gsOk = false; QProcess *procTemp = new QProcess(); procTemp->addArgument(aqApp->gsExecutable()); procTemp->addArgument("--version"); gsOk = procTemp->start(); delete procTemp; if (gsOk) { if (printGhostReport()) return true; } QMessageBox *m = new QMessageBox(tr("Sugerencia"), tr("Si instala Ghostscript (http://www.ghostscript.com) y añade\n" "el directorio de instalación a la ruta de búsqueda de programas\n" "del sistema (PATH), Eneboo podrá utilizarlo para optimizar\n" "sustancialmente la calidad de impresión y para poder generar códigos\nde barras.\n\n"), QMessageBox::Information, QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton, this, 0, false); m->show(); #endif // Get the page count int cnt = report->pageCount(); // Check if there is a report or any pages to print if (cnt == 0) { QMessageBox::critical(this, "Kugar", tr("No hay páginas en el\ninforme para."), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); return false; } // Set the printer dialog printer = new QPrinter(QPrinter::HighResolution); printer->setPageSize((QPrinter::PageSize) report->pageSize()); if ((QPrinter::PageSize) report->pageSize() == QPrinter::Custom) printer->setCustomPaperSize(report->pageDimensions()); printer->setOrientation((QPrinter::Orientation) report->pageOrientation()); printer->setMinMax(1, cnt); printer->setFromTo(1, cnt); printer->setFullPage(true); printer->setColorMode((QPrinter::ColorMode) colorMode_); printer->setNumCopies(numCopies_); printer->setResolution(dpi_); if (!printerName_.isEmpty()) printer->setPrinterName(printerName_); QString printProg(aqApp->printProgram()); if (!printProg.isEmpty()) printer->setPrintProgram(aqApp->printProgram()); bool printNow = true; if (!printerName_.isNull()) printNow = true; else printNow = printer->setup(qApp->focusWidget()); if (printNow) { QPicture *page; QPainter painter; bool printRev = false; // Save the viewer's page index int viewIdx = report->getCurrentIndex(); // Check the order we are printing the pages if (printer->pageOrder() == QPrinter::LastPageFirst) printRev = true; // Get the count of pages and copies to print int printFrom = printer->fromPage() - 1; int printTo = printer->toPage(); int printCnt = (printTo - printFrom); int printCopies = printer->numCopies(); int totalSteps = printCnt * printCopies; int currentStep = 1; // Set copies to 1, QPrinter copies does not appear to work ... printer->setNumCopies(1); // Setup the progress dialog QProgressDialog progress(tr("Imprimiendo Informe..."), tr("Cancelar"), totalSteps, this, tr("progreso"), true); progress.setMinimumDuration(M_PROGRESS_DELAY); QObject::connect(&progress, SIGNAL(cancelled()), this, SLOT(slotCancelPrinting())); progress.setProgress(0); qApp->processEvents(); // Start the printer painter.begin(printer); QPaintDeviceMetrics pdm(printer); QSize dim(report->pageDimensions()); painter.setWindow(0, 0, dim.width(), dim.height()); painter.setViewport(0, 0, pdm.width(), pdm.height()); // Print each copy for (int j = 0; j < printCopies; j++) { // Print each page in the collection for (int i = printFrom; i < printTo; i++, currentStep++) { if (!printer->aborted()) { progress.setProgress(currentStep); qApp->processEvents(); if (printRev) report->setCurrentPage((printCnt == 1) ? i : (printCnt - 1) - i); else report->setCurrentPage(i); page = report->getCurrentPage(); page->play(&painter); if ((i - printFrom) < printCnt - 1) printer->newPage(); } else { j = printCopies; break; } } if (j < printCopies - 1) printer->newPage(); } // Cleanup printing painter.end(); report->setCurrentPage(viewIdx); delete printer; return true; } delete printer; return false; }
void tst_QPicture::devType() { QPicture p; QCOMPARE( p.devType(), (int)QInternal::Picture ); }
int main() { QWidget myWidget; { // RECORD //! [0] QPicture picture; QPainter painter; painter.begin(&picture); // paint in picture painter.drawEllipse(10,20, 80,70); // draw an ellipse painter.end(); // painting done picture.save("drawing.pic"); // save picture //! [0] } { // REPLAY //! [1] QPicture picture; picture.load("drawing.pic"); // load picture QPainter painter; painter.begin(&myImage); // paint in myImage painter.drawPicture(0, 0, picture); // draw the picture at (0,0) painter.end(); // painting done //! [1] } QPicture myPicture; { // FORMATS //! [2] QStringList list = QPicture::inputFormatList(); foreach (QString string, list) myProcessing(string); //! [2] } { // OUTPUT //! [3] QStringList list = QPicture::outputFormatList(); foreach (QString string, list) myProcessing(string); //! [3] } { // PIC READ //! [4] QPictureIO iio; QPixmap pixmap; iio.setFileName("vegeburger.pic"); if (iio.read()) { // OK QPicture picture = iio.picture(); QPainter painter(&pixmap); painter.drawPicture(0, 0, picture); } //! [4] } { QPixmap pixmap; // PIC WRITE //! [5] QPictureIO iio; QPicture picture; QPainter painter(&picture); painter.drawPixmap(0, 0, pixmap); iio.setPicture(picture); iio.setFileName("vegeburger.pic"); iio.setFormat("PIC"); if (iio.write()) return true; // returned true if written successfully //! [5] } }