Exemplo n.º 1
0
ImageArea::ImageArea(const bool &isOpen, const QString &filePath, QWidget *parent) :
    QWidget(parent), mIsEdited(false), mIsPaint(false), mIsResize(false)
{
    setMouseTracking(true);

    mRightButtonPressed = false;
    mFilePath.clear();
    makeFormatsFilters();
    initializeImage();
    mZoomFactor = 1;

    mAdditionalTools = new AdditionalTools(this);

    mUndoStack = new QUndoStack(this);
    mUndoStack->setUndoLimit(DataSingleton::Instance()->getHistoryDepth());

    if(isOpen && filePath.isEmpty())
    {
        open();
    }
    else if(isOpen && !filePath.isEmpty())
    {
        open(filePath);
    }
    else
    {
        QPainter *painter = new QPainter(mImage);
        painter->fillRect(0, 0,
                          DataSingleton::Instance()->getBaseSize().width(),
                          DataSingleton::Instance()->getBaseSize().height(),
                          Qt::white);
        painter->end();

        resize(mImage->rect().right() + 6,
               mImage->rect().bottom() + 6);
    }

    QTimer *autoSaveTimer = new QTimer(this);
    autoSaveTimer->setInterval(DataSingleton::Instance()->getAutoSaveInterval() * 1000);
    connect(autoSaveTimer, SIGNAL(timeout()), this, SLOT(autoSave()));
    connect(mAdditionalTools, SIGNAL(sendNewImageSize(QSize)), this, SIGNAL(sendNewImageSize(QSize)));

    autoSaveTimer->start();

    SelectionInstrument *selectionInstrument = new SelectionInstrument(this);
    connect(selectionInstrument, SIGNAL(sendEnableCopyCutActions(bool)), this, SIGNAL(sendEnableCopyCutActions(bool)));
    connect(selectionInstrument, SIGNAL(sendEnableSelectionInstrument(bool)), this, SIGNAL(sendEnableSelectionInstrument(bool)));

    // Instruments handlers
    mInstrumentsHandlers.fill(0, (int)INSTRUMENTS_COUNT);
    mInstrumentsHandlers[CURSOR] = selectionInstrument;
    mInstrumentsHandlers[PEN] = new PencilInstrument(this);
    mInstrumentsHandlers[LINE] = new LineInstrument(this);
    mInstrumentsHandlers[ERASER] = new EraserInstrument(this);
    mInstrumentsHandlers[RECTANGLE] = new RectangleInstrument(this);
    mInstrumentsHandlers[ELLIPSE] = new EllipseInstrument(this);
    mInstrumentsHandlers[FILL] = new FillInstrument(this);
    mInstrumentsHandlers[SPRAY] = new SprayInstrument(this);
    mInstrumentsHandlers[MAGNIFIER] = new MagnifierInstrument(this);
    mInstrumentsHandlers[COLORPICKER] = new ColorpickerInstrument(this);
    mInstrumentsHandlers[CURVELINE] = new CurveLineInstrument(this);
    mInstrumentsHandlers[TEXT] = new TextInstrument(this);

    // Effects handlers
    mEffectsHandlers.fill(0, (int)EFFECTS_COUNT);
    mEffectsHandlers[NEGATIVE] = new NegativeEffect(this);
    mEffectsHandlers[GRAY] = new GrayEffect(this);
    mEffectsHandlers[BINARIZATION] = new BinarizationEffect(this);
    mEffectsHandlers[GAUSSIANBLUR] = new GaussianBlurEffect(this);
    mEffectsHandlers[GAMMA] = new GammaEffect(this);
    mEffectsHandlers[SHARPEN] = new SharpenEffect(this);
    mEffectsHandlers[CUSTOM] = new CustomEffect(this);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QImage PoleFigureImageUtilities::Create3ImagePoleFigure(UInt8ArrayType* i0, UInt8ArrayType* i1, UInt8ArrayType* i2,
                                                        PoleFigureConfiguration_t& config, int32_t layout)
{

  // Create a QImage that is the width of the first 2 images and the height of the first and third
  QImage img0 = PoleFigureImageUtilities::CreateQImageFromRgbaArray(i0, config.imageDim, true);
  QImage img1 = PoleFigureImageUtilities::CreateQImageFromRgbaArray(i1, config.imageDim, true);
  QImage img2 = PoleFigureImageUtilities::CreateQImageFromRgbaArray(i2, config.imageDim, true);
  // Create the Scalar Bar image
  QImage scalarBar = PoleFigureImageUtilities::GenerateScalarBar(img0.width(), img0.height(), config);

  int pImageWidth = 0;
  int pImageHeight = 0;

  QPoint pos1;
  QPoint pos2;
  QPoint pos3;
  QPoint pos4;

  if(layout == SIMPL::Layout::Horizontal)
  {
    pImageWidth = img0.width() * 4;
    pImageHeight = img0.height();
    pos1 = QPoint(0, 0);
    pos2 = QPoint(img0.width(), 0);
    pos3 = QPoint(img0.width() * 2, 0);
    pos4 = QPoint(img0.width() * 3, 0);
  }
  else if(layout == SIMPL::Layout::Vertical)
  {
    pImageWidth = img0.width();
    pImageHeight = img0.height() * 4;
    pos1 = QPoint(0, 0);
    pos2 = QPoint(0, img0.height());
    pos3 = QPoint(0, img0.height() * 2);
    pos4 = QPoint(0, img0.height() * 3);
  }
  else if(layout == SIMPL::Layout::Square)
  {
    pImageWidth = img0.width() + img1.width();
    pImageHeight = img0.height() + img2.height();
    pos1 = QPoint(0, 0);
    pos2 = QPoint(pImageWidth / 2, 0);
    pos3 = QPoint(0, pImageHeight / 2);
    pos4 = QPoint(pImageWidth / 2, pImageHeight / 2);
  }

  QImage pImage(pImageWidth, pImageHeight, QImage::Format_ARGB32_Premultiplied);
  pImage.fill(0xFFFFFFFF); // All white background

  // Create a Painter backed by a QImage to draw into
  QPainter painter;
  painter.begin(&pImage);
  painter.setRenderHint(QPainter::Antialiasing, true);

  painter.drawImage(pos1, img0); // Draw the first image in the upper Left
  painter.drawImage(pos2, img1); // Draw the second image in the upper right
  painter.drawImage(pos3, img2); // Draw the third image in the lower Left
  painter.drawImage(pos4, scalarBar); // Draw the Scalar Bar

  painter.end();
  // Scale the image down to 225 pixels
  return pImage;
}
Exemplo n.º 3
0
void MainWindow::btnExportClicked()
{
    QList<QChar> charset;

    if (chkLowerAZ->isChecked())
        for (char c = 'a'; c <= 'z'; c++)
            charset.append(c);

    if (chkUpperAZ->isChecked())
        for (char c = 'A'; c <= 'Z'; c++)
            charset.append(c);

    if (chkNumbers->isChecked())
        for (char c = '0'; c <= '9'; c++)
            charset.append(c);

    QString str = ldtCharacters->text();
    for (QString::const_iterator itr(str.begin()); itr != str.end(); itr++)
        if (!charset.contains(*itr))
            charset.append(*itr);

    qSort(charset);

    // Render characters
    QFont font = fontSelector->currentFont();
    font.setPixelSize(font.pointSize());

    QFontMetrics metrics = QFontMetrics(font);
    QTextCodec *codec = QTextCodec::codecForName("utf-8");

    QString glyphs;

    QString fontName = QString("font_%1%2")
            .arg(font.family().toLower())
            .arg(font.pixelSize())
            .replace(' ', '_');

    QString fontstruct = QString(
            "const struct glib_font %1 = {\n"
            "    .charcount = %2,\n"
            "    .size = %3,\n"
            "    .glyphs    = {\n        ")
            .arg(fontName)
            .arg(charset.size())
            .arg(font.pixelSize());

    QListIterator<QChar> itr(charset);
    while (itr.hasNext()) {
        QChar c = itr.next();

        if (c == ' ') {
            // Add space character
            fontstruct += QString("{.utf8 = 0x20, .x = %1, .y = 0, .bitmap = NULL}")
                    .arg(metrics.width(' '));

        } else {
            QRect boundingRect = metrics.boundingRect(c);

            QImage image = QImage(boundingRect.width(), boundingRect.height(),
                    QImage::Format_Mono);

            image.fill(Qt::color1);

            QPainter p;
            p.begin(&image);
            p.setFont(font);
            p.setWindow(metrics.boundingRect(c));
            p.drawText(0, 0, c);
            p.end();

            QString utf8 = codec->fromUnicode(c).toHex();

            glyphs += renderGlyph(utf8, image);
            fontstruct += QString("{.utf8 = 0x%1, .x = %2, .y = %3, .bitmap = &glyph_%1}")
                    .arg(utf8)
                    .arg(boundingRect.x() + 1)
                    .arg(boundingRect.y() - metrics.descent() + 1); // +1 for the base line
        }

        if (itr.hasNext())
            fontstruct += ",\n        ";
    }

    fontstruct += "\n    }\n};\n";

    glyphs = "#include <liblcd/glib.h>\n\n" + glyphs + "\n" + fontstruct;


    QString filename = QFileDialog::getSaveFileName(this,
            tr("Save Font"), fontName + ".c", tr("Source Files (*.c *.cpp)"));

    if (!filename.isEmpty()) {
        if (!(filename.endsWith(".c") || filename.endsWith(".cpp")))
            filename += ".c";

        QFile file(filename);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
            return;

        QTextStream out(&file);
        out << glyphs;
        file.close();
    }
}
Exemplo n.º 4
0
SplashScreen::SplashScreen(QWidget *parent) :
    QWidget(parent)
{

    QRect rec = QApplication::desktop()->screenGeometry();

    int screenWidth = rec.width();
    int screenHeight = rec.height();

    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setGeometry(0,screenHeight/2-150,screenWidth,300);


    QPixmap bgPixmap(screenWidth,300);

    QLinearGradient bgGradient(QPointF(0, 0), QPointF(screenWidth, 0));
    bgGradient.setColorAt(0, QColor("#6c3d94"));
    bgGradient.setColorAt(1, QColor("#a13469"));
    //#3c3c3b

    QRect rect_linear(0,0,screenWidth,300);

    QPainter *painter = new QPainter(&bgPixmap);
    painter->fillRect(rect_linear, bgGradient);

    painter->end();

    bg = new QLabel(this);
    bg->setPixmap(bgPixmap);


    bg->setGeometry(0,0,screenWidth,300);

    splashImage = new QLabel(this);
    QPixmap newPixmap;
    if(GetBoolArg("-testnet")) {
        newPixmap.load(":/images/splash_testnet");
    }
    else {
        newPixmap.load(":/images/splash");
    }


    splashImage->setPixmap(newPixmap);
    splashImage->move(screenWidth/2-567/2,50);


    QFont smallFont; smallFont.setPixelSize(12);

    versionLabel = new QLabel(this);
    versionLabel->setStyleSheet("QLabel { color: #3C3C3B; }");
    versionLabel->setFont(smallFont);
    versionLabel->setText(QString::fromStdString(FormatFullVersion()).split("-")[0]);
    versionLabel->setFixedSize(1000,30);
    versionLabel->move(screenWidth/2-108,220);


    QFont largeFont; largeFont.setPixelSize(20);

    label = new QLabel(this);
    label->setStyleSheet("QLabel { color: #FFFFFF; }");
    label->setFont(largeFont);
    label->setText("...");
    label->setFixedSize(1000,30);
    label->move(screenWidth/2-108,260);

}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QImage PoleFigureImageUtilities::GenerateScalarBar(int imageWidth, int imageHeight, PoleFigureConfiguration_t& config)
{
  int numColors = config.numColors;
  QImage pImage(imageWidth, imageHeight, QImage::Format_ARGB32_Premultiplied);
  pImage.fill(0xFFFFFFFF); // All white background

  // Create a Painter backed by a QImage to draw into
  QPainter painter;
  painter.begin(&pImage);
  painter.setRenderHint(QPainter::Antialiasing, true);

  int penWidth = 1;

#if 0
  // DRAW A BORDER AROUND THE IMAGE FOR DEBUGGING
  QColor c(RgbColor::dRgb(255, 0, 0, 255));
  painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));

  painter.drawLine(0, 0, imageWidth, 0); // Top
  painter.drawLine(0, 0, 0, imageHeight); // Left
  painter.drawLine(imageWidth, 0, imageWidth, imageHeight); // Right
  painter.drawLine(0, imageHeight, imageWidth, imageHeight); // Bottom
  //-----------------
#endif

  //Get all the colors that we will need
  QVector<SIMPL::Rgb> colorTable(numColors);
  QVector<float> colors(3 * numColors, 0.0);
  SIMPLColorTable::GetColorTable(numColors, colors); // Generate the color table values
  float r = 0.0, g = 0.0, b = 0.0;
  for (int i = 0; i < numColors; i++) // Convert them to QRgbColor values
  {
    r = colors[3 * i];
    g = colors[3 * i + 1];
    b = colors[3 * i + 2];
    colorTable[i] = RgbColor::dRgb(r * 255, g * 255, b * 255, 255);
  }

  // Now start from the bottom and draw colored lines up the scale bar
  // A Slight Indentation for the scalar bar
  float margin = 0.05f;
  float scaleBarRelativeWidth = 0.10f;
  float scaleBarRelativeHeight = 1.0f - (margin * 2);

  int colorHeight = int( (imageHeight * scaleBarRelativeHeight) / numColors);

  QPointF topLeft(imageWidth * margin, imageHeight * margin);
  QSizeF size(imageWidth * scaleBarRelativeWidth, imageHeight * scaleBarRelativeHeight);

  int yLinePos = topLeft.y();

  QPointF start = topLeft;
  QPointF end = topLeft;

  for(int i = numColors - 1; i >= 0; i--)
  {
    QColor c(colorTable[i]);
    painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));
    for(int j = 0; j < colorHeight; j++)
    {
      start.setY(yLinePos);
      end.setX(topLeft.x() + (imageWidth * scaleBarRelativeWidth));
      end.setY(yLinePos);
      painter.drawLine(start, end);
      yLinePos++;
    }
  }

  // Draw the border of the scale bar
  size = QSizeF(imageWidth * scaleBarRelativeWidth, numColors * colorHeight); // Add two pixel to the height so we don't over write part of the scale bar
  QRectF scaleBorder(topLeft, size);
  penWidth = 2;
  painter.setPen(QPen(QColor(0, 0, 0, 255), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  painter.drawRect(scaleBorder);


  // Draw the Text Labels of the Scale Bar
  int startFontPtSize = 10;
  QFont font("Ariel", startFontPtSize, QFont::Bold);

  QFontMetrics metrics(font);
  int fontPixelsHeight = metrics.height();
  while(fontPixelsHeight < colorHeight * 2)
  {
    startFontPtSize++;
    font = QFont("Ariel", startFontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    fontPixelsHeight = metrics.height();
  }
  painter.setFont(font);

  // Draw some more information to the right of the Scale Bar
  QString maxStr = QString::number(config.maxScale, 'f', 3);
  painter.drawText(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, topLeft.y() + fontPixelsHeight, maxStr);

  QString minStr = QString::number(config.minScale, 'f', 3);
  painter.drawText(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, topLeft.y() + size.height(), minStr);
  //------------------------------


  // Draw some statistics for the pole figures
  startFontPtSize = 8; // Set it to a rather large point size so we can fit the text perfectly. Only an insanely large Polefigure would go past this size
  int labelWidth = 0;

  // Make sure the size of font we just picked will allow the string to NOT be clipped because the rendered
  // pixel width is past the right side of the image
  int endOfStringYPos = topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10 + labelWidth;
  while(endOfStringYPos < imageWidth)
  {
    startFontPtSize++;
    font = QFont("Ariel", startFontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    QString label("Upper & Lower");
    QString label2 = QString("Samples: ") + QString::number(config.eulers->getNumberOfTuples());
    fontPixelsHeight = metrics.height(); // Update the font height
    int labelWidth = metrics.width(label); // Figure out which string is longer (pixel wise)
    if (labelWidth < metrics.width(label2))
    {
      labelWidth = metrics.width(label2);
    }
    endOfStringYPos = topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10 + labelWidth;
  }
  startFontPtSize--;
  font = QFont("Ariel", startFontPtSize, QFont::Bold);
  metrics = QFontMetrics(font);
  QString label("Upper & Lower");
  QString label2 = QString("Samples: ") + QString::number(config.eulers->getNumberOfTuples());

  labelWidth = metrics.width(label);
  if (labelWidth < metrics.width(label2))
  {
    labelWidth = metrics.width(label2);
  }

  // Set the font into the Painter
  painter.setFont(font);

  QPointF statsPoint(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, imageHeight * .5);

  // Draw some more Statistics Text
  painter.drawText(statsPoint, label);
  statsPoint.setY(imageHeight * .5 + fontPixelsHeight);
  painter.drawText(statsPoint, label2);

  painter.end();
  // Scale the image down to 225 pixels
  return pImage;

}
void QColorTabBar::paintEvent(QPaintEvent *)
{
    //QTabBar::paintEvent(evt);

    QPainter painter;
    painter.begin( this );

    int nDiameter = 3 << 1;
    for( int i=0 ;i<count(); i++ )
    {
        QRect rectTab( tabRect(i).adjusted( 0, 0, -1, 0 ) );

        bool bActive = (m_nActiveIndex == i);
        if( bActive ) rectTab.adjust( 0, 0, 0, 1 );
        bool bHover = (m_nHoverIndex == i);
        bool bNotify = (m_nNotifyIndex == i);

        QPainterPath tabPath;
        QPainterPath tabS;

        QRectF arcRect( 0, 0, nDiameter, nDiameter );

        if (m_bHorz)
        {
            // Horz-Tab
            tabPath.moveTo( rectTab.bottomLeft() );
            tabPath.lineTo( rectTab.left(), rectTab.top()+nDiameter/2);
            tabS.moveTo( rectTab.left(), rectTab.top()+nDiameter/2 );
            arcRect.moveTo( rectTab.topLeft() );
            tabPath.arcTo( arcRect, 180, -90 );
            tabS.arcTo( arcRect, 180, -90 );
            tabPath.lineTo( rectTab.right()-nDiameter/2, rectTab.top() );
            tabS.lineTo( rectTab.right()-nDiameter/2, rectTab.top() );
            arcRect.moveTo( rectTab.right()-nDiameter, rectTab.top() );
            tabPath.arcTo( arcRect, 90, -90 );
            tabS.arcTo( arcRect, 90, -90 );
            tabPath.lineTo( rectTab.bottomRight() );
            //tabS.closeSubpath();
        }
        else
        {
            // Vert-Tab
            tabPath.moveTo( rectTab.right(), rectTab.y() );
            tabPath.lineTo( rectTab.x()+nDiameter, rectTab.y() );
            tabS.moveTo( rectTab.x()+nDiameter, rectTab.y() );
            arcRect.moveTo(rectTab.topLeft());
            tabPath.arcTo( arcRect, -270, 90 );
            tabS.arcTo( arcRect, -270, 90 );
            arcRect.moveTo(rectTab.x(), rectTab.bottom()-nDiameter);
            tabPath.arcTo( arcRect, -180, 90 );
            tabS.arcTo( arcRect, -180, 90 );
            tabPath.moveTo( rectTab.left()+nDiameter, rectTab.bottom() );
            tabPath.lineTo( rectTab.right(), rectTab.bottom() );
            //tabS.closeSubpath();
        }


        QColor colorBody;

        if (bNotify && (m_nBlinkCount % 2 == 0))
        {
            colorBody = QColor(252, 209, 211);
        }
        else
        {
            if (bActive)
                colorBody = QColor(255, 255, 255);
            else
                colorBody = QColor(0xF5, 0xF5, 0xF5);
        }

        painter.fillPath( tabPath, QBrush(colorBody) );

        QColor colorStart = bActive ? g_TabDefaultColor[i] : (bHover ? QColor(255, 190, 60, 200) : QColor(255, 255, 255, 200));
        QColor colorEnd(255, 255, 255, 200);
        QRectF rectTabTip;
        rectTabTip = tabS.boundingRect();
        QLinearGradient gradTip;
        if (m_bHorz)
        {
            gradTip.setStart(rectTabTip.center().x(), rectTabTip.top());
            gradTip.setFinalStop(rectTabTip.center().x(), rectTabTip.bottom());
        }
        else
        {
            gradTip.setStart(rectTabTip.left(), rectTabTip.center().y());
            gradTip.setFinalStop(rectTabTip.right(), rectTabTip.center().y());
        }
        gradTip.setColorAt( 0, colorStart );
        gradTip.setColorAt( 1.f, colorEnd );

        painter.setBrush(Qt::NoBrush);
        painter.setPen( QPen(QColor(160,160,160,100), 2.f) );
        painter.drawPath( tabPath );
        painter.setPen( QPen(QColor(160,160,160)) );
        painter.drawPath( tabPath );
        painter.setPen( Qt::white );
        if( bActive )
            painter.drawLine( rectTab.bottomLeft(), rectTab.bottomRight() );

        painter.fillPath( tabS, QBrush(gradTip) );
        if (bActive || bHover)
        {
            painter.setPen( colorStart );
            painter.drawPath( tabS );
        }

        QRectF rectText;

        float fTextOffset = 0.f;

        if (m_bHorz)
        {
            rectText.setX((float)rectTab.x() + fTextOffset);
            rectText.setY((float)rectTab.y() + nDiameter/2);
            rectText.setWidth((float)rectTab.width() - fTextOffset);
            rectText.setHeight((float)rectTab.height() - nDiameter/2);
        }
        else
        {
            rectText.setX((float)rectTab.x() + nDiameter/2 + fTextOffset);
            rectText.setY((float)rectTab.y());
            rectText.setWidth((float)rectTab.width() - nDiameter/2 - fTextOffset);
            rectText.setHeight((float)rectTab.height());
        }

        QFont fnt( font() );

        fnt.setBold(bActive);

        painter.setFont( fnt );

        int flags = Qt::AlignCenter|Qt::AlignVCenter|Qt::TextSingleLine;
        painter.setPen( QColor(80,80,80) );
        painter.drawText( rectText, flags, tabText(i) );

        if( m_nBlinkIndex == i && m_bBlinkFalg )
        {
            painter.fillPath( tabPath, QColor(240,240,0,128) );
        }
    }

    painter.end();
}
Exemplo n.º 7
0
void Printer::render(int Pages = 0)
{
	// keep original preferences
	QPointer<ProfileWidget2> profile = MainWindow::instance()->graphics();
	int profileFrameStyle = profile->frameStyle();
	int animationOriginal = prefs.animation_speed;
	double fontScale = profile->getFontPrintScale();
	double printFontScale = 1.0;

	// apply printing settings to profile
	profile->setFrameStyle(QFrame::NoFrame);
	profile->setPrintMode(true, !printOptions->color_selected);
	profile->setToolTipVisibile(false);
	prefs.animation_speed = 0;

	// render the Qwebview
	QPainter painter;
	QRect viewPort(0, 0, pageSize.width(), pageSize.height());
	painter.begin(paintDevice);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);

	// get all refereces to diveprofile class in the Html template
	QWebElementCollection collection = webView->page()->mainFrame()->findAllElements(".diveprofile");

	QSize originalSize = profile->size();
	if (collection.count() > 0) {
		printFontScale = (double)collection.at(0).geometry().size().height() / (double)profile->size().height();
		profile->resize(collection.at(0).geometry().size());
	}
	profile->setFontPrintScale(printFontScale);

	int elemNo = 0;
	for (int i = 0; i < Pages; i++) {
		// render the base Html template
		webView->page()->mainFrame()->render(&painter, QWebFrame::ContentsLayer);

		// render all the dive profiles in the current page
		while (elemNo < collection.count() && collection.at(elemNo).geometry().y() < viewPort.y() + viewPort.height()) {
			// dive id field should be dive_{{dive_no}} se we remove the first 5 characters
			QString diveIdString = collection.at(elemNo).attribute("id");
			int diveId = diveIdString.remove(0, 5).toInt(0, 10);
			putProfileImage(collection.at(elemNo).geometry(), viewPort, &painter, get_dive_by_uniq_id(diveId), profile);
			elemNo++;
		}

		// scroll the webview to the next page
		webView->page()->mainFrame()->scroll(0, pageSize.height());
		viewPort.adjust(0, pageSize.height(), 0, pageSize.height());

		// rendering progress is 4/5 of total work
		emit(progessUpdated((i * 80.0 / Pages) + done));
		if (i < Pages - 1 && printMode == Printer::PRINT)
			static_cast<QPrinter*>(paintDevice)->newPage();
	}
	painter.end();

	// return profle settings
	profile->setFrameStyle(profileFrameStyle);
	profile->setPrintMode(false);
	profile->setFontPrintScale(fontScale);
	profile->setToolTipVisibile(true);
	profile->resize(originalSize);
	prefs.animation_speed = animationOriginal;

	//replot the dive after returning the settings
	profile->plotDive(0, true);
}
Exemplo n.º 8
0
void DockWnd::timer()
{
    if (++m_state >= 4) m_state = 0;
    ShowIcon needIcon = State;
    bool bBlinked = pClient->isConnecting();
    unsigned short msgType = 0;
    if (pMain->messages.size()) msgType = pMain->messages.back().type();
    switch (m_state){
    case 1:
        if (msgType){
            needIcon = Message;
        }else if (bBlinked){
            needIcon = Blinked;
        }
        break;
    case 2:
        if (msgType && bBlinked)
            needIcon = Blinked;
        break;
    case 3:
        if (msgType){
            needIcon = Message;
        }else if (bBlinked){
            needIcon = Blinked;
        }
        break;
    }
    if (needIcon == showIcon) return;
    showIcon = needIcon;
    switch (showIcon){
    case State:
        setIcon(Pict(pClient->getStatusIcon()));
        break;
    case Message:
        setIcon(Pict(SIMClient::getMessageIcon(msgType)));
        break;
    case Blinked:
        setIcon(Pict(SIMClient::getStatusIcon(ICQ_STATUS_ONLINE)));
        break;
    default:
        break;
    }
#ifndef WIN32
    if (inTray) return;
    const char *icon = pClient->getStatusIcon();
    const char *msg  = NULL;
    const char *bmsg = NULL;
    if (msgType) bmsg = SIMClient::getMessageIcon(msgType);
    if (bBlinked){
        if (m_state & 1){
            icon = SIMClient::getStatusIcon(ICQ_STATUS_ONLINE);
        }else{
            msg = bmsg;
        }
    }else{
        if (!(m_state & 1)){
            msg = bmsg;
        }
    }
    if (wharfIcon){
        wharfIcon->set(icon, msg);
        return;
    }
    const QIconSet &icons = Icon(icon);
    QPixmap nvis(icons.pixmap(QIconSet::Large, QIconSet::Normal));
    if (!bEnlightenment){
        resize(nvis.width(), nvis.height());
        if (msg){
            QPixmap msgPict = Pict(msg);
            QRegion *rgn = NULL;
            if (nvis.mask() && msgPict.mask()){
                rgn = new QRegion(*msgPict.mask());
                rgn->translate(nvis.width() - msgPict.width() - SMALL_PICT_OFFS,
                               nvis.height() - msgPict.height() - SMALL_PICT_OFFS);
                *rgn += *nvis.mask();
            }
            QPainter p;
            p.begin(&nvis);
            p.drawPixmap(nvis.width() - msgPict.width() - SMALL_PICT_OFFS,
                         nvis.height() - msgPict.height() - SMALL_PICT_OFFS, msgPict);
            p.end();
            if (rgn){
                setMask(*rgn);
                delete rgn;
            }
        }else{
            const QBitmap *mask = nvis.mask();
            if (mask) setMask(*mask);
        }
    }
    drawIcon = nvis;
    repaint();
#endif
}
Exemplo n.º 9
0
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!!";
    }

}
Exemplo n.º 10
0
int bandageImage(QStringList arguments)
{
    QTextStream out(stdout);
    QTextStream err(stderr);

    if (checkForHelp(arguments))
    {
        printImageUsage(&out, false);
        return 0;
    }

    if (checkForHelpAll(arguments))
    {
        printImageUsage(&out, true);
        return 0;
    }

    if (arguments.size() < 2)
    {
        printImageUsage(&err, false);
        return 1;
    }

    QString graphFilename = arguments.at(0);
    arguments.pop_front();

    if (!checkIfFileExists(graphFilename))
    {
        err << "Bandage error: " << graphFilename << " does not exist" << endl;
        return 1;
    }

    QString imageSaveFilename = arguments.at(0);
    arguments.pop_front();

    QString imageFileExtension = imageSaveFilename.right(4);
    bool pixelImage;
    if (imageFileExtension == ".png" || imageFileExtension == ".jpg")
        pixelImage = true;
    else if (imageFileExtension == ".svg")
        pixelImage = false;
    else
    {
        err << "Bandage error: the output filename must end in .png, .jpg or .svg" << endl;
        return 1;
    }

    QString error = checkForInvalidImageOptions(arguments);
    if (error.length() > 0)
    {
        err << "Bandage error: " << error << endl;
        return 1;
    }

    bool loadSuccess = g_assemblyGraph->loadGraphFromFile(graphFilename);
    if (!loadSuccess)
    {
        err << "Bandage error: could not load " << graphFilename << endl;
        return 1;
    }

    int width = 0;
    int height = 0;
    parseImageOptions(arguments, &width, &height);

    //For Bandage image, it is necessary to position node labels at the
    //centre of the node, not the visible centre(s).  This is because there
    //is no viewport.
    g_settings->positionTextNodeCentre = true;

    //Since frame rate performance doesn't matter for a fixed image, set the
    //default node outline to a nonzero value.
    g_settings->outlineThickness = 0.3;

    bool blastUsed = isOptionPresent("--query", &arguments);

    if (blastUsed)
    {
        if (!createBlastTempDirectory())
        {
            err << "Error creating temporary directory for BLAST files" << endl;
            return 1;
        }

        QString blastError = g_blastSearch->doAutoBlastSearch();

        if (blastError != "")
        {
            err << blastError << endl;
            return 1;
        }
    }

    QString errorTitle;
    QString errorMessage;
    std::vector<DeBruijnNode *> startingNodes = g_assemblyGraph->getStartingNodes(&errorTitle, &errorMessage,
                                                                                  g_settings->doubleMode,
                                                                                  g_settings->startingNodes,
                                                                                  "all");

    if (errorMessage != "")
    {
        err << errorMessage << endl;
        return 1;
    }

    g_assemblyGraph->buildOgdfGraphFromNodesAndEdges(startingNodes, g_settings->nodeDistance);
    g_assemblyGraph->layoutGraph();

    MyGraphicsScene scene;
    g_assemblyGraph->addGraphicsItemsToScene(&scene);
    scene.setSceneRectangle();
    double sceneRectAspectRatio = scene.sceneRect().width() / scene.sceneRect().height();

    //Determine image size
    //If neither height nor width set, use a default of height = 1000.
    if (height == 0 && width == 0)
        height = 1000;

    //If only height or width is set, scale the other to fit.
    if (height > 0 && width == 0)
        width = height * sceneRectAspectRatio;
    else if (height == 0 && width > 0)
        height = width / sceneRectAspectRatio;

    bool success = true;
    QPainter painter;
    if (pixelImage)
    {
        QImage image(width, height, QImage::Format_ARGB32);
        image.fill(Qt::white);
        painter.begin(&image);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setRenderHint(QPainter::TextAntialiasing);
        scene.render(&painter);
        success = image.save(imageSaveFilename);
        painter.end();
    }
    else //SVG
    {
        QSvgGenerator generator;
        generator.setFileName(imageSaveFilename);
        generator.setSize(QSize(width, height));
        generator.setViewBox(QRect(0, 0, width, height));
        painter.begin(&generator);
        painter.fillRect(0, 0, width, height, Qt::white);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setRenderHint(QPainter::TextAntialiasing);
        scene.render(&painter);
        painter.end();
    }

    int returnCode;
    if (!success)
    {
        out << "There was an error writing the image to file." << endl;
        returnCode = 1;
    }
    else
        returnCode = 0;

    if (blastUsed)
        deleteBlastTempDirectory();

    return returnCode;
}
Exemplo n.º 11
0
void dialogAnalog::fillPixmap(CData *data, QPen *dataPen)
{
    mainwindow->analogMutex.lock();
	TAnalog_Data plot,next_plot;
	QPainter painter;
    int heightPerField = lastPixmap.height() / NbBits;
	
	painter.begin(&lastPixmap);
	painter.setPen(*dataPen);

    QVector< QVector<QPoint> > polyline(64);

    Qt::CheckState csMarker = chkBShowMarker->checkState();

    for (int j=1;j<data->size();j++)
	{
		plot = data->Read(j-1);
		next_plot = data->Read(j);

		int current = heightPerField;
		int X1,Y1,X2,Y2;
		
		X1=StateToX(plot.state);
		X2=StateToX(next_plot.state);

        // Crop to the visible area
        if (!( (j>1) && ( (X2<0) || ( X1>frame_dataview->width())))) {

            for (int jj=0;jj<NbBits;jj++)
            {
                //#define READ_BIT(b,p)	( ((b)>>(p)) & 0x01 ? 1 :0 )
                Y1= current - READ_BIT(plot.values,jj)* 3 * heightPerField / 5;
                Y2= current - READ_BIT(next_plot.values,jj)* 3 * heightPerField / 5;
                //painter.drawLine(X1,Y1,X2,Y1);
                //painter.drawLine(X2,Y1,X2,Y2);
                polyline[jj].append( QPoint(X1,Y1) );
                polyline[jj].append( QPoint(X2,Y1) );
                current += heightPerField;
            }

            // plot the Markers
            // Need to optimize
            if ( plot.marker && (csMarker == Qt::Checked) ) {
                QPen pen((Qt::white));
                pen.setStyle(Qt::DotLine);
                painter.setPen(pen);
                painter.drawLine(X1,12,X1,height());
                // set font ------------------------------------------------------------------------------------
                QFont textFont;
                textFont.setPixelSize(10);
                painter.setFont(textFont);
                painter.drawText(X1, 11, QString::number(plot.marker,10));
                painter.setPen(*dataPen);
            }
        }
	}
    if (polyline.size()) {
        for (int jj=0;jj<NbBits;jj++)
        {
            if (polyline[jj].size())
                painter.drawPolyline(polyline[jj].data(),polyline[jj].size());
        }
    }
	painter.end();
    mainwindow->analogMutex.unlock();
}
Exemplo n.º 12
0
void DBThread::TriggerMapRendering()
{
  RenderMapRequest request;
  {
    QMutexLocker locker(&mutex);

    request=currentRenderRequest;
    if (!doRender) {
      return;
    }



    renderBreaker->Reset();
  }

  if (currentImage==NULL ||
      currentImage->width()!=(int)request.width ||
      currentImage->height()!=(int)request.height) {
    delete currentImage;

    currentImage=new QImage(QSize(request.width,request.height),QImage::Format_RGB32);
  }

  currentLon=request.lon;
  currentLat=request.lat;
  currentAngle=request.angle;
  currentMagnification=request.magnification;
  QPainter p;
  if (database->IsOpen() &&
      styleConfig) {
    osmscout::MapParameter        drawParameter;
    osmscout::AreaSearchParameter searchParameter;

    searchParameter.SetBreaker(renderBreakerRef);
    searchParameter.SetMaximumAreaLevel(4);
    searchParameter.SetUseMultithreading(currentMagnification.GetMagnification()<=osmscout::Magnification::magCity);

    std::list<std::string>        paths;

    paths.push_back(iconDirectory.toLocal8Bit().data());

    drawParameter.SetIconPaths(paths);
    drawParameter.SetPatternPaths(paths);
    drawParameter.SetDebugPerformance(true);
    drawParameter.SetOptimizeWayNodes(osmscout::TransPolygon::quality);
    drawParameter.SetOptimizeAreaNodes(osmscout::TransPolygon::quality);
    drawParameter.SetRenderSeaLand(true);
    drawParameter.SetBreaker(renderBreakerRef);
    double fs = drawParameter.GetFontSize();
    QSettings s;
    double fsMul = s.value("fontSize", 1).toDouble();
    qDebug()<<"FontSize: "<<fs;
    qDebug()<<"DPI:" << dpi;
    fs*=(dpi/50)*fsMul; //for 100DPI, multiply by 1.5
    drawParameter.SetFontSize(fs);

    std::cout << std::endl;

    osmscout::StopClock overallTimer;

    projection.Set(currentLon,
                   currentLat,
                   currentAngle,
                   currentMagnification,
                   dpi,
                   request.width,
                   request.height);

    osmscout::StopClock dataRetrievalTimer;

    mapService->GetObjects(searchParameter,
                           styleConfig,
                           projection,
                           data);

    if (drawParameter.GetRenderSeaLand()) {
      mapService->GetGroundTiles(projection,
                                 data.groundTiles);
    }

    dataRetrievalTimer.Stop();

    osmscout::StopClock drawTimer;



    p.begin(currentImage);
    p.setRenderHint(QPainter::Antialiasing);
    p.setRenderHint(QPainter::TextAntialiasing);
    p.setRenderHint(QPainter::SmoothPixmapTransform);

    painter->DrawMap(projection,
                     drawParameter,
                     data,
                     &p);

    p.end();

    drawTimer.Stop();
    overallTimer.Stop();

    std::cout << "All: " << overallTimer << " Data: " << dataRetrievalTimer << " Draw: " << drawTimer << std::endl;
  }
  else {
    std::cout << "Cannot draw map: " << database->IsOpen() << " " << styleConfig.Valid() << std::endl;

    p.begin(currentImage);
    p.setRenderHint(QPainter::Antialiasing);
    p.setRenderHint(QPainter::TextAntialiasing);
    p.setRenderHint(QPainter::SmoothPixmapTransform);

    p.fillRect(0,0,request.width,request.height,
               QColor::fromRgbF(0.0,0.0,0.0,1.0));

    p.setPen(QColor::fromRgbF(1.0,1.0,1.0,1.0));

    QString text("not initialized (yet)");

    p.drawText(QRect(0,0,request.width,request.height),
               Qt::AlignCenter|Qt::AlignVCenter,
               text,
               NULL);

    p.end();
  }

  QMutexLocker locker(&mutex);

  if (renderBreaker->IsAborted()) {
    return;
  }

  std::swap(currentImage,finishedImage);
  std::swap(currentLon,finishedLon);
  std::swap(currentLat,finishedLat);
  std::swap(currentAngle,finishedAngle);
  std::swap(currentMagnification,finishedMagnification);
  doRender=false;
  emit HandleMapRenderingResult();
}
Exemplo n.º 13
0
void RulerT::paintEvent(QPaintEvent *)
{
	double xl;
	QPainter p;
	p.begin(this);
	p.drawLine(0, 24, width(), 24);
	p.translate(-offset, 0);
	p.setBrush(Qt::black);
	p.setFont(font());
	p.setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
	for (xl = 0; xl < width()+offset; xl += iter)
	{
		if (xl < offset)
			continue;
		p.drawLine(qRound(xl), 18, qRound(xl), 24);
	}
	for (xl = 0; xl < width()+(iter2/2)+offset; xl += iter2)
	{
		if (xl < offset)
			continue;
		p.drawLine(qRound(xl), 11, qRound(xl), 24);
		switch (unitIndex)
		{
			case 2:
			{
				QString tx = "";
				int num1 = static_cast<int>(xl / iter2);
				if (num1 != 0)
					tx = QString::number(num1);
				double frac = (xl / iter2) - num1;
				if ((frac > 0.24) && (frac < 0.26))
					tx += QChar(0xBC);
				if ((frac > 0.49) && (frac < 0.51))
					tx += QChar(0xBD);
				if ((frac > 0.74) && (frac < 0.76))
					tx += QChar(0xBE);
				p.drawText(qRound(xl+2), 17, tx);
				break;
			}
			case 3:
				p.drawText(qRound(xl+2), 17, QString::number(xl / iter));
				break;
			default:
				p.drawText(qRound(xl+2), 17, QString::number(xl / iter * 10));
				break;
		}
	}
	if (tabValues.count() != 0)
	{
		for (int yg = 0; yg < static_cast<int>(tabValues.count()); yg++)
		{
			if (yg == actTab)
				p.setPen(QPen(Qt::red, 2, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
			else
				p.setPen(QPen(Qt::black, 2, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
			switch (static_cast<int>(tabValues[yg].tabType))
			{
				case 0:
					p.drawLine(qRound(tabValues[yg].tabPosition), 15, qRound(tabValues[yg].tabPosition), 23);
					p.drawLine(qRound(tabValues[yg].tabPosition), 23, qRound(tabValues[yg].tabPosition+8), 23);
					break;
				case 1:
					p.drawLine(qRound(tabValues[yg].tabPosition), 15, qRound(tabValues[yg].tabPosition), 23);
					p.drawLine(qRound(tabValues[yg].tabPosition), 23, qRound(tabValues[yg].tabPosition-8), 23);
					break;
				case 2:
				case 3:
					p.drawLine(qRound(tabValues[yg].tabPosition), 15, qRound(tabValues[yg].tabPosition), 23);
					p.drawLine(qRound(tabValues[yg].tabPosition-4), 23, qRound(tabValues[yg].tabPosition+4), 23);
					p.drawLine(qRound(tabValues[yg].tabPosition+3), 20, qRound(tabValues[yg].tabPosition+2), 20);
					break;
				case 4:
					p.drawLine(qRound(tabValues[yg].tabPosition), 15, qRound(tabValues[yg].tabPosition), 23);
					p.drawLine(qRound(tabValues[yg].tabPosition-4), 23, qRound(tabValues[yg].tabPosition+4), 23);
					break;
				default:
					break;
			}
		}
	}
	if (haveInd)
	{
		p.setPen(QPen(Qt::blue, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
		p.setBrush(Qt::blue);
		QPolygon cr;
		cr.setPoints(3, qRound(firstLine+leftIndent), 12, qRound(firstLine+leftIndent-4), 0, qRound(firstLine+leftIndent+4), 0);
		p.drawPolygon(cr);
		QPolygon cr2;
		cr2.setPoints(3, qRound(leftIndent), 12, qRound(leftIndent+4), 24, qRound(leftIndent-4), 24);
		p.drawPolygon(cr2);
	}
	p.end();
}
QImage* QgsPieDiagramFactory::createDiagram( int size, const QgsFeature& f, const QgsRenderContext& renderContext ) const
{
  QgsAttributeMap dataValues = f.attributeMap();
  double sizeScaleFactor = diagramSizeScaleFactor( renderContext );

  //create transparent QImage
  int imageSideLength = size * sizeScaleFactor * renderContext.rasterScaleFactor() + 2 * mMaximumPenWidth + 2 * mMaximumGap;
  QImage* diagramImage = new QImage( QSize( imageSideLength, imageSideLength ), QImage::Format_ARGB32_Premultiplied );
  diagramImage->fill( qRgba( 0, 0, 0, 0 ) ); //transparent background
  QPainter p;
  p.begin( diagramImage );
  p.setRenderHint( QPainter::Antialiasing );
  p.setPen( Qt::NoPen );

  //calculate sum of data values
  double sum = 0;
  QList<double> valueList; //cash the values to use them in drawing later

  QgsAttributeMap::const_iterator value_it;
  QList<QgsDiagramCategory>::const_iterator it = mCategories.constBegin();
  for ( ; it != mCategories.constEnd(); ++it )
  {
    value_it = dataValues.find( it->propertyIndex() );
    valueList.push_back( value_it->toDouble() );
    if ( value_it != dataValues.constEnd() )
    {
      sum += value_it->toDouble();
    }
  }

  if ( doubleNear( sum, 0.0 ) )
  {
    p.end();
    delete diagramImage;
    return 0;
  }

  //draw pies

  int totalAngle = 0;
  int currentAngle, currentGap;
  int xGapOffset = 0;
  int yGapOffset = 0;

  QList<QgsDiagramCategory>::const_iterator category_it = mCategories.constBegin();
  QList<double>::const_iterator valueList_it = valueList.constBegin();

  for ( ; category_it != mCategories.constEnd() && valueList_it != valueList.constEnd(); ++category_it, ++valueList_it )
  {
    p.setPen( category_it->pen() );
    currentAngle = ( int )(( *valueList_it ) / sum * 360 * 16 );
    p.setBrush( category_it->brush() );

    xGapOffset = 0;
    yGapOffset = 0;
    currentGap = category_it->gap();
    if ( currentGap != 0 )
    {
      //qt angles are degrees*16
      gapOffsetsForPieSlice( currentGap, totalAngle + currentAngle / 2, xGapOffset, yGapOffset );
    }

    p.drawPie( mMaximumPenWidth * renderContext.rasterScaleFactor() + mMaximumGap + xGapOffset, mMaximumPenWidth * renderContext.rasterScaleFactor() + mMaximumGap - yGapOffset, sizeScaleFactor * renderContext.rasterScaleFactor() * size, sizeScaleFactor * renderContext.rasterScaleFactor() * size, totalAngle, currentAngle );
    totalAngle += currentAngle;
  }
  p.end();

  return diagramImage;
}
Exemplo n.º 15
0
// public virtual [base kpCommand]
void kpToolAutoCropCommand::unexecute ()
{
#if DEBUG_KP_TOOL_AUTO_CROP && 1
    kdDebug () << "kpToolAutoCropCommand::unexecute()" << endl;
#endif

    kpDocument *doc = document ();
    if (!doc)
        return;

    QPixmap pixmap (m_oldWidth, m_oldHeight);
    QBitmap maskBitmap;

    // restore the position of the centre image
    kpPixmapFX::setPixmapAt (&pixmap, m_contentsRect,
                             *doc->pixmap (m_actOnSelection));

    // draw the borders

    QPainter painter (&pixmap);
    QPainter maskPainter;

    const kpToolAutoCropBorder *borders [] =
    {
        &m_leftBorder, &m_rightBorder,
        &m_topBorder, &m_botBorder,
        0
    };

    const QPixmap *pixmaps [] =
    {
        m_leftPixmap, m_rightPixmap,
        m_topPixmap, m_botPixmap,
        0
    };

    const QPixmap **p = pixmaps;
    for (const kpToolAutoCropBorder **b = borders; *b; b++, p++)
    {
        if (!(*b)->exists ())
            continue;

        if ((*b)->isSingleColor ())
        {
            kpColor col = (*b)->referenceColor ();
#if DEBUG_KP_TOOL_AUTO_CROP && 1
            kdDebug () << "\tdrawing border " << (*b)->rect ()
                       << " rgb=" << (int *) col.toQRgb () /* %X hack */ << endl;
#endif

            if (col.isOpaque ())
            {
                painter.fillRect ((*b)->rect (), col.toQColor ());
            }
            else
            {
                if (maskBitmap.isNull ())
                {
                    // TODO: dangerous when a painter is active on pixmap?
                    maskBitmap = kpPixmapFX::getNonNullMask (pixmap);
                    maskPainter.begin (&maskBitmap);
                }

                maskPainter.fillRect ((*b)->rect (), Qt::color0/*transparent*/);
            }
        }
        else
        {
#if DEBUG_KP_TOOL_AUTO_CROP && 1
            kdDebug () << "\trestoring border pixmap " << (*b)->rect () << endl;
#endif
            // **p cannot contain a single transparent pixel because
            // if it did, all other pixels must be transparent (only
            // transparent pixels are similar to transparent pixels)
            // and the other branch would execute.
            if (*p)
            {
                // TODO: We should really edit the mask here.  Due to good
                //       luck (if "maskBitmap" is initialized above, this region
                //       will be marked as opaque in the mask; if it's not
                //       initialized, we will be opaque by default), we
                //       don't actually have to edit the mask but this is
                //       highly error-prone.
                painter.drawPixmap ((*b)->rect (), **p);
            }
        }
    }

    if (maskPainter.isActive ())
        maskPainter.end ();

    painter.end ();

    if (!maskBitmap.isNull ())
        pixmap.setMask (maskBitmap);


    if (!m_actOnSelection)
        doc->setPixmap (pixmap);
    else
    {
        kpSelection sel = m_oldSelection;
        sel.setPixmap (pixmap);

        doc->setSelection (sel);

        if (m_mainWindow->tool ())
            m_mainWindow->tool ()->somethingBelowTheCursorChanged ();
    }


    deleteUndoPixmaps ();
}
Exemplo n.º 16
0
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!!";
    }
}
Exemplo n.º 17
0
void
PlayField::mouseMoveEvent(QMouseEvent *e) {
  lastMouseXPos_ = e->x();
  lastMouseYPos_ = e->y();

  if (!dragInProgress_) return highlight();

  int old_x = dragX_, old_y = dragY_;

  dragX_ = lastMouseXPos_ - mousePosX_;
  dragY_ = lastMouseYPos_ - mousePosY_;

  {
    int x = pixel2x(dragX_ + size_/2);
    int y = pixel2y(dragY_ + size_/2);
    if (x >= 0 && x < levelMap_->width() &&
	y >= 0 && y < levelMap_->height() &&
	pathFinder_.canDragTo(x, y)) {
      x = x2pixel(x);
      y = y2pixel(y);

      if (dragX_ >= x - size_/4 &&
	  dragX_ <  x + size_/4 &&
	  dragY_ >= y - size_/4 &&
	  dragY_ <  y + size_/4) {
	dragX_ = x;
	dragY_ = y;
      }
    }
  }

  if (dragX_ == old_x && dragY_ == old_y) return;

  QRect rect(dragX_, dragY_, size_, size_);

  dragXpm_= QPixmap(size_, size_);

  QPainter paint;
  paint.begin(&dragXpm_);
  paint.setBackground(palette().color(backgroundRole()));
  paint.setBrushOrigin(- dragX_, - dragY_);
  paint.translate((double) (- dragX_), (double) (- dragY_));
  paintPainter(paint, rect);
  paint.end();

  dragImage_ = dragXpm_.toImage();
  for (int yy=0; yy<size_; yy++) {
    for (int xx=0; xx<size_; xx++) {
      QRgb rgb1 = imageData_->objectImg().pixel(xx, yy);
      int r1 = qRed(rgb1);
      int g1 = qGreen(rgb1);
      int b1 = qBlue(rgb1);
      if (r1 != g1 || r1 != b1 || r1 == 255) {
	QRgb rgb2 = dragImage_.pixel(xx, yy);
	int r2 = qRed(rgb2);
	int g2 = qGreen(rgb2);
	int b2 = qBlue(rgb2);
	r2 = (int) (0.75 * r1 + 0.25 * r2 + 0.5);
	g2 = (int) (0.75 * g1 + 0.25 * g2 + 0.5);
	b2 = (int) (0.75 * b1 + 0.25 * b2 + 0.5);
	dragImage_.setPixel(xx, yy, qRgb(r2, g2, b2));
      }
    }
  }

  paint.begin(this);

  // the following line is a workaround for a bug in Qt 2.0.1
  // (and possibly earlier versions)
  paint.setBrushOrigin(0, 0);

  dragXpm_ = QPixmap::fromImage(dragImage_,
			    Qt::OrderedDither|Qt::OrderedAlphaDither|
			    Qt::ColorOnly|Qt::AvoidDither);
  paint.drawPixmap(dragX_, dragY_, dragXpm_);

  {
    int dx = dragX_ - old_x;
    int dy = dragY_ - old_y;
    int y2 = old_y;
    if (dy > 0) {
      paintPainterClip(paint, old_x, old_y, size_, dy);
      // NOTE: clipping is now activated in the QPainter paint
      y2 += dy;
    } else if (dy < 0) {
      paintPainterClip(paint, old_x, old_y+size_+dy, size_, -dy);
      // NOTE: clipping is now activated in the QPainter paint
      dy = -dy;
    }
    if (dx > 0) {
      paintPainterClip(paint, old_x, y2, dx, size_-dy);
      // NOTE: clipping is now activated in the QPainter paint
    } else if (dx < 0) {
      paintPainterClip(paint, old_x+size_+dx, y2, -dx, size_-dy);
      // NOTE: clipping is now activated in the QPainter paint
    }
  }
  paint.end();
}
Exemplo n.º 18
0
bool rasterizePolygons(QString const &outputFolder,
                       QList<QList<Vec2d> > const &listPolygons)
{
    qDebug() << "INFO: Rasterizing polys to images in" << outputFolder;
    int kSzMult=100;

    QImage shImage1(180*kSzMult,180*kSzMult,
                    QImage::Format_RGB888);

    QImage shImage2(180*kSzMult,180*kSzMult,
                    QImage::Format_RGB888);

    shImage1.fill(Qt::white);
    shImage2.fill(Qt::white);

    // setup painter
    QPainter shPainter;
    QBrush shBrush(Qt::blue);

    // draw polys on image 1
    shPainter.begin(&shImage1);
    shPainter.setPen(Qt::NoPen);
    for(int i=0; i < listPolygons.size(); i++)
    {
        QPainterPath pPath;
        pPath.setFillRule(Qt::WindingFill);
        pPath.moveTo(listPolygons[i][0].x*kSzMult,
                     listPolygons[i][0].y*kSzMult);

        for(int j=0; j < listPolygons[i].size(); j++)   {
            pPath.lineTo(listPolygons[i][j].x*kSzMult,
                         listPolygons[i][j].y*kSzMult);
        }
        pPath.closeSubpath();

        shBrush.setColor(listPolygons[i][0].c);
        shPainter.setBrush(shBrush);
        shPainter.drawPath(pPath);
    }
    shPainter.end();

    // draw polys on image2
    shPainter.begin(&shImage2);
    shPainter.setPen(Qt::NoPen);
    for(int i=0; i < listPolygons.size(); i++)
    {
        QPainterPath pPath;
        pPath.setFillRule(Qt::WindingFill);
        pPath.moveTo(listPolygons[i][0].x*kSzMult - 180*kSzMult,
                     listPolygons[i][0].y*kSzMult);

        for(int j=0; j < listPolygons[i].size(); j++)   {
            pPath.lineTo(listPolygons[i][j].x*kSzMult - 180*kSzMult,
                         listPolygons[i][j].y*kSzMult);
        }
        pPath.closeSubpath();

        shBrush.setColor(listPolygons[i][0].c);
        shPainter.setBrush(shBrush);
        shPainter.drawPath(pPath);
    }
    shPainter.end();

    QString fname1 = outputFolder + "/imgW.png";
    QString fname2 = outputFolder + "/imgE.png";

    if(shImage1.save(fname1) && shImage2.save(fname2))   {
        qDebug() << "INFO: Saved images as" << fname1
                 << "and" << fname2;
        return true;
    }

    qDebug() << "ERROR: Could not save images";
    return false;
}
Exemplo n.º 19
0
void ColorCombo::addColors()
{
  QRect rect( 0, 0, width(), 20 );
  QPixmap pixmap( rect.width(), rect.height() );
  QPainter painter;
  QPen pen;
  int i;

  clear();

  for ( i = 0; i < STANDARD_PAL_SIZE; i++ )
    if ( standardPalette[i] == internalcolor ) break;

  if ( i == STANDARD_PAL_SIZE )
    customColor = internalcolor;

  insertItem( i18n("None") );

  if ( qGray( customColor.rgb() ) < 128 )
    pen.setColor( white );
  else
    pen.setColor( black );

  painter.begin( &pixmap );
  QBrush brush( customColor );
  painter.fillRect( rect, brush );
  painter.setPen( pen );

  painter.drawText( 2, painter.fontMetrics().height(), i18n("Custom...") );
  painter.end();

  insertItem( pixmap );
  pixmap.detach();

  bool findColor = false;

  for ( i = 0; i < STANDARD_PAL_SIZE; i++ )
  {
    painter.begin( &pixmap );
    QBrush brush( standardPalette[i] );
    painter.fillRect( rect, brush );
    painter.end();

    insertItem( pixmap );
    pixmap.detach();

    if ( standardPalette[i] == internalcolor ) {
      setCurrentItem( i + 2 );
      findColor = true;
    }
  }

  if ( !findColor )
    setCurrentItem(1);



  if ( !hascolor )
    setCurrentItem(0);

}
Exemplo n.º 20
0
void WindowServerLuna::generateWallpaperImages()
{
	qreal hScale, vScale, wallpaperScale, wallpaperScaleRot = 0.0;

	int screenWidth = SystemUiController::instance()->currentUiWidth();
	int screenHeight = SystemUiController::instance()->currentUiHeight();

	QPixmap image = QPixmap(m_wallpaperFileName);
	if (image.isNull())
		return;

	bool desktop(false);
#ifdef TARGET_DESKTOP
	desktop = true;
#endif

	if(((image.width() < screenWidth) || (image.height() < screenHeight)) && ((image.height() < screenWidth) || (image.width() < screenHeight)) && !desktop) {
		// image is not large enough to fill the screen in any orientation, so do not scale it and
		// draw it centered on the screen
		m_normalWallpaperImage = QPixmap(image.width(), image.height());
		m_rotatedWallpaperImage = QPixmap();

		wallpaperScale = 1;
		m_wallpaperFullScreen = false;
		if (m_normalWallpaperImage.isNull())
			return;
	} else {
		// image can fill the screen in some orientations, so scale it to always fill the entire screen
		m_normalWallpaperImage = QPixmap(m_screenWidth, m_screenHeight);
		m_rotatedWallpaperImage = QPixmap(m_screenWidth, m_screenHeight);

		hScale = (qreal)m_screenWidth / image.width();
		vScale = (qreal)m_screenHeight / image.height();

		if(hScale >= vScale)
			wallpaperScale = hScale;
		else
			wallpaperScale = vScale;

		vScale = (qreal)m_screenHeight / image.width();
		hScale = (qreal)m_screenWidth / image.height();

		if(hScale >= vScale)
			wallpaperScaleRot = hScale;
		else
			wallpaperScaleRot = vScale;

		m_wallpaperFullScreen = true;

		if (m_normalWallpaperImage.isNull())
			return;
		if (m_rotatedWallpaperImage.isNull())
			return;
	}

	QRect target;
	QPainter painter;
	painter.begin(&m_normalWallpaperImage);

	target = QRect((-image.rect().width()/2), (-image.rect().height()/2), image.rect().width(), image.rect().height());

	painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
	painter.translate(m_normalWallpaperImage.width()/2, m_normalWallpaperImage.height()/2);
	painter.scale(wallpaperScale,wallpaperScale);

	painter.drawPixmap(target, image);

	painter.end();

	if(m_wallpaperFullScreen) {// also generate the cropped and rotated version
		painter.begin(&m_rotatedWallpaperImage);

		target = QRect((-image.rect().width()/2), (-image.rect().height()/2), image.rect().width(), image.rect().height());

		painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
		painter.translate(m_rotatedWallpaperImage.width()/2, m_rotatedWallpaperImage.height()/2);
		painter.rotate(90);
		painter.scale(wallpaperScaleRot,wallpaperScaleRot);

		painter.drawPixmap(target, image);

		painter.end();
	}

	if(Settings::LunaSettings()->displayUiRotates) {
		updateWallpaperForRotation(m_currentUiOrientation);
	} else {
		m_currWallpaperImg = &m_normalWallpaperImage;
		Q_EMIT signalWallpaperImageChanged(m_currWallpaperImg, m_wallpaperFullScreen, 0);
	}
}
Exemplo n.º 21
0
/** This is overloaded function. It's version for SVG vector image.
  *
  * Sets required image size.
  * \return negative value when an error has occured
  * \return 0 when an unsupported SharedInformation::sizeUnit value was set
  * \return 1 when success (for 2 (\e bytes) value of SharedInformation::sizeUnit only)
  */
char ConvertThread::computeSize(QSvgRenderer *renderer, const QString &imagePath) {
    QSize defaultSize = renderer->defaultSize();
    if (shared.sizeUnit == 0) // px
    // compute size when it wasn't typed in pixels
        return 1;
    else if (shared.sizeUnit == 1) { // %
        width *= defaultSize.width() / 100.;
        height *= defaultSize.height() / 100.;
        return 1;
    }
    else if (shared.sizeUnit == 2) { // bytes
        width = defaultSize.width();
        height = defaultSize.height();
        hasWidth = true;
        hasHeight = true;
        double destSize = shared.sizeBytes;
        if (isLinearFileSizeFormat(&destSize)) {
            double sourceSizeSqrt = sqrt(width * height);
            double sourceWidthRatio = width / sourceSizeSqrt;
            double sourceHeightRatio = height / sourceSizeSqrt;
            destSize = sqrt(destSize);
            width = sourceWidthRatio * destSize;
            height = sourceHeightRatio * destSize;
        }
        else { // non-linear size relationship
            QString tempFilePath = QDir::tempPath() + QDir::separator() +
                    "sir_temp" + QString::number(tid) + "." + shared.format;
            qint64 fileSize = QFile(imagePath).size();
            QSize size = defaultSize;
            double fileSizeRatio = (double) fileSize / shared.sizeBytes;
            fileSizeRatio = sqrt(fileSizeRatio);
            QFile tempFile(tempFilePath);
            QPainter painter;
            for (uchar i=0; i<10 && (fileSizeRatio<0.97412 || fileSizeRatio>1.); i++) {
                tempFile.open(QIODevice::WriteOnly);
                tempFile.seek(0);
                width = size.width() / fileSizeRatio;
                height = size.height() / fileSizeRatio;
                QImage tempImage(width, height, QImage::Format_ARGB32);
                fillImage(&tempImage);
                painter.begin(&tempImage);
                renderer->render(&painter);
                painter.end();
                tempImage = paintEffects(&tempImage);
                tempImage = rotateImage(tempImage);
#ifdef SIR_METADATA_SUPPORT
                updateThumbnail(tempImage);
#endif // SIR_METADATA_SUPPORT
                if (tempImage.save(&tempFile, 0, shared.quality)) {
#ifdef SIR_METADATA_SUPPORT
                    if (saveMetadata)
                        metadata.write(tempFilePath, tempImage);
#endif // SIR_METADATA_SUPPORT
                }
                else {
                    qWarning("tid %d: Save temporary image file "
                             "into %s failed", tid,
                             String(targetFilePath).
                                toNativeStdString().data());
                    emit imageStatus(imageData, tr("Failed to compute image size"),
                                     Failed);
                    return -4;
                }
                tempFile.close();
                fileSize = tempFile.size();
                size = tempImage.size();
                fileSizeRatio = (double) fileSize / shared.sizeBytes;
                fileSizeRatio = sqrt(fileSizeRatio);
            }
            // ask overwrite
            char answer = askOverwrite(&tempFile);
            if (answer < 0)
                return answer;
        }
        return 2;
    }
    return 0;
}
Exemplo n.º 22
0
void TimeRuler::initUI() {
    int width = m_widthMonth + (m_lstDates.numYears() * 12 ) * m_widthMonth + m_widthMonth;

    m_pixmap = QPixmap(width, m_height);
    m_pixmap.fill(backgroundColor());

    QPainter p (&m_pixmap);

    p.save();

    p.setPen(Qt::gray);
    p.setBrush(Qt::white);
    QStyle& style = KApplication::kApplication()->style();

    //draw a frame
    QColorGroup cg = colorGroup();
    cg.setColor(QColorGroup::Background, Qt::white);

    style.drawPrimitive(QStyle::PE_ButtonBevel, &p,
                        QRect(m_widthMonth, 3, width - 2 * m_widthMonth, m_yBase - 3), cg);

    p.restore();

    //first create the month counter on a temporaroy pixmap
    QPixmap tp(12 * m_widthMonth, 20);
    tp.fill(backgroundColor());
    QPainter tpp (&tp);
    tpp.translate(0,20);
    tpp.rotate(-90);

    QFont f(p.font());
    f.setPixelSize(10);
    f.setBold(false);
    tpp.setFont(f);

    for (int i = 0; i <12; ++i) {
        tpp.drawText(0, i * m_widthMonth, 20, m_widthMonth, Qt::AlignRight | Qt::AlignVCenter, QString::number(i+1));
    }
    tpp.end();


    int over = -2;
    int x = 0;

   //reset the counting mechanism...
    m_lstDates.count(-1);

    for (int y = m_lstDates.firstYear(); y <= m_lstDates.lastYear(); ++ y) {
        for (int m = 1; m <= 12 ; ++m) {

            x = m_widthMonth + ((y - m_lstDates.firstYear())*12 + m -1 ) * m_widthMonth;

            if (m == 1) {
                bitBlt(&m_pixmap, x, m_yBase + 3, &tp, 0, 0, tp.width(), tp.height());

                //draw the year numbers
                f.setPixelSize(16);
                f.setBold(true);
                p.setFont(f);
                p.drawText(x, m_yBase, 12 * m_widthMonth, m_height-m_yBase, Qt::AlignHCenter | Qt::AlignBottom, QString::number(y));

                //draw the bold year lines
                p.setPen(QPen(Qt::gray, 3));
                p.drawLine(x, m_yBase+over, x, m_yBase+22);
                p.setPen(QPen(Qt::black, 1));
                p.drawLine(x, m_yBase+over, x, m_yBase+22);
            } else if (m == 7) {
                //draw the semi big half year marks
                p.setPen(QPen(Qt::gray, 3));
                p.drawLine(x, m_yBase+over, x, m_yBase+8);
                p.setPen(QPen(Qt::black, 1));
                p.drawLine(x, m_yBase+over, x, m_yBase+8);
            } else {
                //draw the thin month marks
                p.setPen(QPen(Qt::black, 1));
                p.drawLine(x, m_yBase+over, x, m_yBase+8);
            }
            drawBeam(&p, m_lstDates.count(y,m, -1, true) * 100 / m_lstDates.maxMonth(), y, m);
        }
    }
    //draw the final year bar thats missing from the loop
    x += m_widthMonth;
    p.setPen(QPen(Qt::gray, 3));
    p.drawLine(x, m_yBase+over, x, m_yBase+22);
    p.setPen(QPen(Qt::black, 1));
    p.drawLine(x, m_yBase+over, x, m_yBase+22);


    //now draw the base line
    p.setPen(QPen(Qt::black, 1));
    p.drawLine(10, m_yBase, width - 10 , m_yBase);

    //done
    p.end();
}
Exemplo n.º 23
0
void MainWindow::drawGraph(bool notEmpty)
{
    QPixmap graph(540,370);
    QPainter paint;
    paint.begin(&graph);
    paint.eraseRect(0,0,540,370);
    paint.drawLine(Ox*onePixelX,0,Ox*onePixelX,pictHeight);
    paint.drawLine(0,Oy*onePixelY,pictWidth,Oy*onePixelY);

    paint.setPen(QPen(Qt::black,3));
    for(double i = leftX;i<=rightX;i+=10.0)
        paint.drawPoint((i+Ox)*onePixelX,Oy*onePixelY);
    for(double i = leftY;i<=rightY;i+=10.0)
        paint.drawPoint(Ox*onePixelX,(i+Oy)*onePixelY);

    if(!notEmpty) {
        paint.end();
        ui->outputGraph->setPixmap(graph);
        return;
    }

    paint.setPen(QPen(Qt::green,1,Qt::SolidLine));
    paint.setRenderHint(QPainter::Antialiasing, true);
    QPainterPath path,p[3];
    bool first[4] = {1,1,1,1};

    for(double i = (double)leftX+step;i<=(double)rightX;i+=step) {
        if(!isnan(f(i))) {
            if(first[0]) {
                path.moveTo((i+Ox)*onePixelX,(f(i)+Oy)*onePixelY);
                first[0] = false;
            }
            else
                path.lineTo((i+Ox)*onePixelX,(f(i)+Oy)*onePixelY);
        }
        if(!isnan(f1(i))) {
            if(first[1]) {
                p[0].moveTo((i+Ox)*onePixelX,(f1(i)+Oy)*onePixelY);
                first[1] = false;
            }
            else
                p[0].lineTo((i+Ox)*onePixelX,(f1(i)+Oy)*onePixelY);
        }
        if(!isnan(f2(i))) {
            if(first[2]) {
                p[1].moveTo((i+Ox)*onePixelX,(f2(i)+Oy)*onePixelY);
                first[2] = false;
            }
            else
                p[1].lineTo((i+Ox)*onePixelX,(f2(i)+Oy)*onePixelY);
        }
        if(!isnan(f3(i))) {
            if(first[3]) {
                p[2].moveTo((i+Ox)*onePixelX,(f3(i)+Oy)*onePixelY);
                first[3] = false;
            }
            else
                p[2].lineTo((i+Ox)*onePixelX,(f3(i)+Oy)*onePixelY);
        }
    }
    if(ui->main->isChecked()) {
        paint.setPen(QPen(Qt::blue,1,Qt::SolidLine));
        paint.drawPath(path);
    }
    if(ui->sin->isChecked()) {
        paint.setPen(QPen(Qt::green,1,Qt::SolidLine));
        paint.drawPath(p[0]);
    }
    if(ui->cos->isChecked()) {
        paint.setPen(QPen(Qt::red,1,Qt::SolidLine));
        paint.drawPath(p[1]);
    }
    if(ui->tg->isChecked()) {
        paint.setPen(QPen(Qt::darkMagenta,1,Qt::SolidLine));
        paint.drawPath(p[2]);
    }
    paint.end();
    ui->outputGraph->setPixmap(graph);
    return;
}
Exemplo n.º 24
0
void GLView::paintEvent( QPaintEvent * event )
{
	makeCurrent();

	QPainter painter;
	painter.begin( this );
	painter.setRenderHint( QPainter::TextAntialiasing );
#else
void GLView::paintGL()
{
#endif
	

	// Save GL state
	glPushAttrib( GL_ALL_ATTRIB_BITS );
	glMatrixMode( GL_PROJECTION );
	glPushMatrix();
	glMatrixMode( GL_MODELVIEW );
	glPushMatrix();

	// Clear Viewport
	if ( scene->visMode & Scene::VisSilhouette ) {
		qglClearColor( QColor( 255, 255, 255, 255 ) );
	}
	//glViewport( 0, 0, width(), height() );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
	
	
	// Compile the model
	if ( doCompile ) {
		textures->setNifFolder( model->getFolder() );
		scene->make( model );
		scene->transform( Transform(), scene->timeMin() );
		axis = (scene->bounds().radius <= 0) ? 1024.0 : scene->bounds().radius;

		if ( scene->timeMin() != scene->timeMax() ) {
			if ( time < scene->timeMin() || time > scene->timeMax() )
				time = scene->timeMin();

			emit sequencesUpdated();

		} else if ( scene->timeMax() == 0 ) {
			// No Animations in this NIF
			emit sequencesDisabled( true );
		}
		emit sceneTimeChanged( time, scene->timeMin(), scene->timeMax() );
		doCompile = false;
	}

	// Center the model
	if ( doCenter ) {
		setCenter();
		doCenter = false;
	}

	// Transform the scene
	Matrix ap;

	// TODO: Redo for new Settings class
	//if ( Options::upAxis() == Options::YAxis ) {
	//	ap( 0, 0 ) = 0; ap( 0, 1 ) = 0; ap( 0, 2 ) = 1;
	//	ap( 1, 0 ) = 1; ap( 1, 1 ) = 0; ap( 1, 2 ) = 0;
	//	ap( 2, 0 ) = 0; ap( 2, 1 ) = 1; ap( 2, 2 ) = 0;
	//} else if ( Options::upAxis() == Options::XAxis ) {
	//	ap( 0, 0 ) = 0; ap( 0, 1 ) = 1; ap( 0, 2 ) = 0;
	//	ap( 1, 0 ) = 0; ap( 1, 1 ) = 0; ap( 1, 2 ) = 1;
	//	ap( 2, 0 ) = 1; ap( 2, 1 ) = 0; ap( 2, 2 ) = 0;
	//}

	Transform viewTrans;
	viewTrans.rotation.fromEuler( Rot[0] / 180.0 * PI, Rot[1] / 180.0 * PI, Rot[2] / 180.0 * PI );
	viewTrans.rotation = viewTrans.rotation * ap;
	viewTrans.translation = viewTrans.rotation * Pos;

	if ( view != ViewWalk )
		viewTrans.translation[2] -= Dist * 2;

	scene->transform( viewTrans, time );

	// Setup projection mode
	glProjection();
	glLoadIdentity();

	// Draw the grid
	if ( scene->options & Scene::ShowAxes ) {
		glDisable( GL_ALPHA_TEST );
		glDisable( GL_BLEND );
		glDisable( GL_LIGHTING );
		glDisable( GL_COLOR_MATERIAL );
		glEnable( GL_DEPTH_TEST );
		glDepthMask( GL_TRUE );
		glDepthFunc( GL_LESS );
		glDisable( GL_TEXTURE_2D );
		glDisable( GL_NORMALIZE );
		glLineWidth( 2.0f );

		glPushMatrix();
		glLoadMatrix( viewTrans );

		// TODO: Configurable grid in Settings
		// 1024 game units, major lines every 128, minor lines every 64
		drawGrid( 1024, 128, 2 );

		glPopMatrix();
	}

#ifndef QT_NO_DEBUG
	// Debug scene bounds
	glEnable( GL_DEPTH_TEST );
	glDepthMask( GL_TRUE );
	glDepthFunc( GL_LESS );
	glPushMatrix();
	glLoadMatrix( viewTrans );
	if ( debugMode == DbgBounds ) {
		BoundSphere bs = scene->bounds();
		bs |= BoundSphere( Vector3(), axis );
		drawSphere( bs.center, bs.radius );
	}
	glPopMatrix();
#endif

	GLfloat mat_spec[] = { 0.0f, 0.0f, 0.0f, 1.0f };

	if ( scene->options & Scene::DoLighting ) {
		// Setup light
		Vector4 lightDir( 0.0, 0.0, 1.0, 0.0 );

		if ( !frontalLight ) {
			float decl = declination / 180.0 * PI;
			Vector3 v( sin( decl ), 0, cos( decl ) );
			Matrix m; m.fromEuler( 0, 0, planarAngle / 180.0 * PI );
			v = m * v;
			lightDir = Vector4( viewTrans.rotation * v, 0.0 );

			if ( scene->visMode & Scene::VisLightPos ) {
				glEnable( GL_BLEND );
				glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
				glEnable( GL_DEPTH_TEST );
				glDepthMask( GL_TRUE );
				glDepthFunc( GL_LESS );

				glPushMatrix();
				glLoadMatrix( viewTrans );

				glLineWidth( 2.0f );
				glColor4f( 1.0f, 1.0f, 1.0f, 0.5f );

				// Scale the distance a bit
				float l = axis + 64.0;
				l = (l < 128) ? axis * 1.5 : l;
				l = (l > 2048) ? axis * 0.66 : l;
				l = (l > 1024) ? axis * 0.75 : l;

				drawDashLine( Vector3( 0, 0, 0 ), v * l, 30 );
				drawSphere( v * l, axis / 10 );
				glPopMatrix();
				glDisable( GL_BLEND );
			}
		}

		float amb = ambient;
		if ( (scene->visMode & Scene::VisNormalsOnly)
			&& (scene->options & Scene::DoTexturing)
			&& !(scene->options & Scene::DisableShaders) )
		{
			amb = 0.1f;
		}
		
		GLfloat mat_amb[] = { amb, amb, amb, 1.0f };
		GLfloat mat_diff[] = { brightness, brightness, brightness, 1.0f };
		

		glShadeModel( GL_SMOOTH );
		glEnable( GL_LIGHTING );
		glEnable( GL_LIGHT0 );
		glLightfv( GL_LIGHT0, GL_AMBIENT, mat_amb );
		glLightfv( GL_LIGHT0, GL_DIFFUSE, mat_diff );
		glLightfv( GL_LIGHT0, GL_SPECULAR, mat_diff );
		glLightfv( GL_LIGHT0, GL_POSITION, lightDir.data() );

		// Necessary?
		glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE );
	} else {
		float amb = 0.5f;
		if ( scene->options & Scene::DisableShaders ) {
			amb = 0.0f;
		}

		GLfloat mat_amb[] = { amb, amb, amb, 1.0f };
		GLfloat mat_diff[] = { 1.0f, 1.0f, 1.0f, 1.0f };
		

		glShadeModel( GL_SMOOTH );
		glEnable( GL_LIGHTING );
		glEnable( GL_LIGHT0 );
		glLightfv( GL_LIGHT0, GL_AMBIENT, mat_amb );
		glLightfv( GL_LIGHT0, GL_DIFFUSE, mat_diff );
		glLightfv( GL_LIGHT0, GL_SPECULAR, mat_spec );
	}

	if ( scene->visMode & Scene::VisSilhouette ) {
		GLfloat mat_diff[] = { 0.0f, 0.0f, 0.0f, 1.0f };
		GLfloat mat_amb[] = { 0.0f, 0.0f, 0.0f, 1.0f };

		glShadeModel( GL_FLAT );
		glEnable( GL_LIGHTING );
		glEnable( GL_LIGHT0 );
		glLightModelfv( GL_LIGHT_MODEL_AMBIENT, mat_diff );
		glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_diff );
		glLightfv( GL_LIGHT0, GL_AMBIENT, mat_amb );
		glLightfv( GL_LIGHT0, GL_DIFFUSE, mat_diff );
		glLightfv( GL_LIGHT0, GL_SPECULAR, mat_spec );
	}

	if ( scene->options & Scene::DoMultisampling )
		glEnable( GL_MULTISAMPLE_ARB );

#ifndef QT_NO_DEBUG
	// Color Key debug
	if ( debugMode == DbgColorPicker ) {
		glDisable( GL_MULTISAMPLE );
		glDisable( GL_LINE_SMOOTH );
		glDisable( GL_TEXTURE_2D );
		glDisable( GL_BLEND );
		glDisable( GL_DITHER );
		glDisable( GL_LIGHTING );
		glShadeModel( GL_FLAT );
		glDisable( GL_FOG );
		glDisable( GL_MULTISAMPLE_ARB );
		glEnable( GL_DEPTH_TEST );
		glDepthFunc( GL_LEQUAL );
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
		Node::SELECTING = 1;
	} else {
		Node::SELECTING = 0;
	}
#endif

	// Draw the model
	scene->draw();

	if ( scene->options & Scene::ShowAxes ) {
		// Resize viewport to small corner of screen
		int axesSize = std::min( width() / 10, 125 );
		glViewport( 0, 0, axesSize, axesSize );

		// Reset matrices
		glMatrixMode( GL_PROJECTION );
		glLoadIdentity();

		// Square frustum
		auto nr = 1.0;
		auto fr = 250.0;
		GLdouble h2 = tan( FOV / 360 * M_PI ) * nr;
		GLdouble w2 = h2;
		glFrustum( -w2, +w2, -h2, +h2, nr, fr );

		// Reset matrices
		glMatrixMode( GL_MODELVIEW );
		glLoadIdentity();

		glPushMatrix();

		// Store and reset viewTrans translation
		auto viewTransOrig = viewTrans.translation;

		// Zoom out slightly
		viewTrans.translation = { 0, 0, -150.0 };

		// Load modified viewTrans
		glLoadMatrix( viewTrans );

		// Restore original viewTrans translation
		viewTrans.translation = viewTransOrig;

		// Find direction of axes
		auto vtr = viewTrans.rotation;
		QVector<float> axesDots = { vtr( 2, 0 ), vtr( 2, 1 ), vtr( 2, 2 ) };

		drawAxesOverlay( { 0, 0, 0 }, 50.0, sortAxes( axesDots ) );

		glPopMatrix();

		// Restore viewport size
		glViewport( 0, 0, width(), height() );
		// Restore matrices
		glProjection();
	}

	// Restore GL state
	glPopAttrib();
	glMatrixMode( GL_MODELVIEW );
	glPopMatrix();
	glMatrixMode( GL_PROJECTION );
	glPopMatrix();

	// Check for errors
	GLenum err;
	while ( ( err = glGetError() ) != GL_NO_ERROR )
		qDebug() << tr( "glview.cpp - GL ERROR (paint): " ) << (const char *)gluErrorString( err );

	emit paintUpdate();

	// Manually handle the buffer swap
	swapBuffers();

#ifdef USE_GL_QPAINTER
	painter.end();
#endif
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QImage PoleFigureImageUtilities::PaintPoleFigureOverlay(int imageWidth, int imageHeight, QString label, QImage image)
{
  int pxHigh = 0;
  int pxWide = 0;

  // Scale the Font Point size to something reasonable to the size of the image. Here our standard was 14Pt Font when the
  // Pole figure was 512 Pixels square.
  int fontPtSize = imageHeight / 32;

  QFont font("Ariel", fontPtSize, QFont::Bold);
  QFontMetrics metrics(font);
  pxHigh = metrics.height();
  pxWide = metrics.width(QString("Y"));

  int pxOffset = 2 * pxWide;
  int pyOffset = 2 * pxHigh;

  int pImageWidth = imageWidth + pxOffset * 2;
  int pImageHeight = imageHeight + pyOffset * 2;

  QImage pImage(pImageWidth, pImageHeight, QImage::Format_ARGB32_Premultiplied);
  pImage.fill(0xFFFFFFFF); // All white background

  // Create a Painter backed by a QImage to draw into
  QPainter painter;
  painter.begin(&pImage);
  painter.setRenderHint(QPainter::Antialiasing, true);
  qint32 penWidth = 1;

#if 0
  // DRAW A BORDER AROUND THE IMAGE FOR DEBUGGING
  QColor c(RgbColor::dRgb(255, 0, 0, 255));
  painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));

  painter.drawLine(0, 0, pImageWidth, 0); // Top
  painter.drawLine(0, 0, 0, pImageHeight); // Left
  painter.drawLine(pImageWidth, 0, pImageWidth, pImageHeight); // Right
  painter.drawLine(0, pImageHeight, pImageWidth, pImageHeight); // Bottom
  //-----------------
#endif

  painter.setFont(font);
//  metrics = painter.fontMetrics();
//  pxHigh = metrics.height();
//  pxWide = metrics.width(QString("Y"));

  // Draw the Pole Figure into the center of the canvas
  QPoint point(pxOffset, pyOffset);
  painter.drawImage(point, image);

  // Scale pen width based on the size of the image
  penWidth = imageHeight / 256;
  painter.setPen(QPen(QColor(0, 0, 0, 255), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));

  // Draw the Outer circular border around the pole figure
  QPainterPath circle;
  QPointF center(pImageWidth / 2, pImageHeight / 2);
  circle.addEllipse(center, imageWidth / 2, imageHeight / 2);
  painter.drawPath(circle);

  // Label the X Axis
  painter.drawText(pImageWidth - (pxWide * 1.5), pImageHeight / 2 + pxHigh / 3, "X");
  // Label the Y Axis
  pxWide = metrics.width(QString("Y"));
  painter.drawText(pImageWidth / 2 - pxWide / 2, pyOffset - penWidth - 1, "Y");

  // Draw the name of the Pole Figure
  int labelWidth = 0;
  int maxWidth = pImageWidth / 5; // No more than a Quarter of the width of the image
  while(labelWidth < maxWidth)
  {
    fontPtSize++;
    font = QFont("Ariel", fontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    labelWidth = metrics.width(label); // Figure out which string is longer (pixel wise)
  }
  painter.setFont(font);
  pxHigh = metrics.height() + 2;
// pxWide = metrics.width(label);
  painter.drawText(pxOffset, pxHigh, label);

  // Draw slightly transparent lines
  //penWidth = 1;
  painter.setPen(QPen(QColor(0, 0, 0, 180), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  // Draw the X Axis
  painter.drawLine(pxOffset, pImageHeight / 2, pImageWidth - pxOffset, pImageHeight / 2);
  // Draw the Y Axis
  painter.drawLine(pImageWidth / 2, pyOffset, pImageWidth / 2, pImageHeight - pyOffset);

  painter.end();
  return pImage;
}
Exemplo n.º 26
0
void MapScene::add_mark(QPointF pos, Tag mark,Channel channel)
{
    QPointF posForPicture = QPointF(pos.x()-12.0, pos.y()-12.0);
    //QPointF posForText = QPointF(pos.x()-24.0, pos.y()+24.0);
    QGraphicsPixmapItem * pi = 0;
    QString channel_name = channel.getName();
    if(channel_name == "Fuel prices")
    {
        pi = addPixmap(QPixmap(":/img/fuel.png"));
    }
    else if(channel_name == "Public announcements")
    {
        pi = addPixmap(QPixmap(":/img/public.png"));
    }
    else if(channel_name == "ObsTestChannel")
    {
        pi = addPixmap(QPixmap(":/img/test.png"));
        //painter.drawText(posForText, "Test text");
    }
    else if(channel_name.startsWith("bus_"))
    {
        pi = addPixmap(QPixmap(":/img/bus.png"));
        //painter.drawText(posForText, channel_name.split('_').at(1));
    }
    else if(channel_name.startsWith("tram_"))
    {
        pi = addPixmap(QPixmap(":/img/tram.png"));
        //painter.drawText(posForText, channel_name.split('_').at(1));
    }
    else if(channel_name.startsWith("troll_"))
    {
        pi = addPixmap(QPixmap(":/img/trolleybus.png"));
        //painter.drawText(posForText, channel_name.split('_').at(1));
    }
    else if(channel_name.startsWith("user_"))
    {
        pi = addPixmap(QPixmap(":/img/user.png"));
    }
    else
    {
        QPixmap pixmap(50,50);
        pixmap.fill(Qt::transparent);
        QPoint center(pixmap.width()/2, pixmap.height()/4);
        QPoint posForText = QPoint(0, pixmap.height()/2+8);
        QPainter painter;
        painter.begin(&pixmap);
        QFont font=painter.font();
        font.setPointSize(7);
        painter.setFont(font);
        painter.setBrush(Qt::blue);
        painter.drawEllipse(center, pixmap.width()/4, pixmap.height()/4);
        painter.setBrush(Qt::black);
        painter.drawEllipse(center, pixmap.width()/10, pixmap.height()/10);
        int mins_ago=(mark.getTime().toUTC().secsTo(QDateTime::currentDateTime()))/60;
        qDebug() << "Text for mark: " << mark.getLabel()+", "+ QString::number(mins_ago)+" min. ago" ;
        painter.drawText(posForText,QString::number(mins_ago)+" min ago");
        painter.end();

        pi = this->addPixmap(pixmap);
    }

    pi->setX(posForPicture.x());
    pi->setY(posForPicture.y());

    m_marks.push_back(pi);
}
Exemplo n.º 27
0
void MainWidget::paintGL()
{

    makeCurrent();

    QPainter painter;
    painter.begin(this);
    painter.beginNativePainting();

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Enable depth buffer

    if(bDepthTest)
        glEnable(GL_DEPTH_TEST);

    QQuaternion quat = this->trackball.rotation();

    // Calculate model view transformation
    QMatrix4x4 modelviewearth;
    modelviewearth.translate(0.0, 0.0, distance);
    modelviewearth.rotate(quat);

    QMatrix4x4 rotmatrix;
    rotmatrix.rotate(quat);

    programskybox.bind();
    skybox->render(projection, modelviewearth, rotmatrix);
    programskybox.release();


    if(bWireFrame) // Draw as wireframe
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    else
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    if(bTexture)
    {
        if(bNoBump)
        {
            programearthnobump.bind();
            textureearth->bind(0);
            geometries->render(projection, modelviewearth, bNoBump);
            textureearth->release();
            programearthnobump.release();
        }
        else
        {
            programearth.bind();
            textureearth->bind(0);
            texturenormal->bind(1);
            geometries->render(projection, modelviewearth, bNoBump);

            texturenormal->release();
            textureearth->release();
            programearth.release();
        }
    }

    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    if(bBorders)
    {
        programgshhs.bind();
        gshhs->render(projection, modelviewearth);
        gshhs->rendersoc(projection, modelviewearth);
        programgshhs.release();
    }

    glDisable(GL_DEPTH_TEST);

    painter.endNativePainting();

    QString framesPerSecond;
    if (const int elapsed = m_time.elapsed()) {
        framesPerSecond.setNum(m_frames /(elapsed / 1000.0), 'f', 2);
        painter.setPen(Qt::white);
        painter.drawText(20, 40, framesPerSecond + " paintGL calls / s");
    }

    //this->setWindowTitle(framesPerSecond + " paintGL calls / s" );

    painter.end();

    if (!(m_frames % 100)) {
        m_time.start();
        m_frames = 0;
    }
    ++m_frames;

}
Exemplo n.º 28
0
void ScalePlot::drawScale ()
{
  QPainter painter;
  painter.begin(&buffer);
  painter.setFont(plotFont);
  painter.setPen(QPen(borderColor, 1, QPen::SolidLine));

  painter.fillRect(0, 0, buffer.width(), buffer.height(), backgroundColor);
  
  QMemArray<double> scaleArray;
  scaler.getScaleArray(scaleArray);
  
  QFontMetrics fm(plotFont);

  int x = 0;
  int loop;
  for (loop = 0; loop < (int) scaleArray.size(); loop++)
  {
    int y = scaler.convertToY(scaleArray[loop]);
    painter.drawLine (x, y, x + 4, y);

    // draw the text
    QString s;
    strip(scaleArray[loop], 4, s);
    
    // abbreviate too many (>=3) trailing zeroes in large numbers on y-axes
    if (! mainFlag)
    {
      bool flag = FALSE;
      
      if (s.toDouble() < 0)
      {
        flag = TRUE;
	s.remove(0, 1);  
      }
      
      if (s.toDouble() >= 1000000000)
      {
        strip(s.toDouble() / 1000000000, 4, s);
	s.append("b");
      }
      else
      {
        if (s.toDouble() >= 1000000)
        {
          strip(s.toDouble() / 1000000, 4, s);
	  s.append("m");
        }
//        else
//        {
//          if (s.toDouble() >= 1000)
//          {
//            strip(s.toDouble() / 1000, 4, s);
//            s.append("k");
//          }
//        }
      }
      
      if (flag)
        s.prepend("-");
    }
    
    painter.drawText(x + 7, y + (fm.height() / 2), s);
  }

  painter.drawLine (x, 0, x, buffer.height());
  
  // draw the last value pointer on the scale of main plot
  int y = scaler.convertToY(close);
    
  QPointArray array;
  array.setPoints(3, x + 2, y,
                  x + 8, y - 4,
                  x + 8, y + 4);
  painter.setBrush(borderColor);
  painter.drawPolygon(array, TRUE, 0, -1);

  painter.end();
}
Exemplo n.º 29
0
  ~TestFixtureForPaintingWindowDrawingMethods()
  {
    _painter.end();

    _test_window->scrollArea()->deleteLater();
  }
Exemplo n.º 30
0
void ImageArea::drawCursor()
{
    QPainter painter;
    mPixmap = new QPixmap(25, 25);
    QPoint center(13, 13);
    switch(DataSingleton::Instance()->getInstrument())
    {
    case NONE_INSTRUMENT: case LINE: case COLORPICKER: case MAGNIFIER: case  SPRAY:
    case FILL: case RECTANGLE: case ELLIPSE: case CURSOR: case INSTRUMENTS_COUNT:
    case CURVELINE: case TEXT:
        break;
    case PEN: case ERASER:
        mPixmap->fill(QColor(0, 0, 0, 0));
        break;
    }
    painter.begin(mPixmap);
    switch(DataSingleton::Instance()->getInstrument())
    {
    case NONE_INSTRUMENT: case LINE: case COLORPICKER: case MAGNIFIER: case  SPRAY:
    case FILL: case RECTANGLE: case ELLIPSE: case CURSOR: case INSTRUMENTS_COUNT:
    case CURVELINE: case TEXT:
        break;
    case PEN:
        if(mRightButtonPressed)
        {
            painter.setPen(QPen(DataSingleton::Instance()->getSecondaryColor()));
            painter.setBrush(QBrush(DataSingleton::Instance()->getSecondaryColor()));
        }
        else
        {
            painter.setPen(QPen(DataSingleton::Instance()->getPrimaryColor()));
            painter.setBrush(QBrush(DataSingleton::Instance()->getPrimaryColor()));
        }
        painter.drawEllipse(center, DataSingleton::Instance()->getPenSize()/2,
                        DataSingleton::Instance()->getPenSize()/2);
        break;
    case ERASER:
        painter.setBrush(QBrush(Qt::white));
        painter.drawEllipse(center, DataSingleton::Instance()->getPenSize()/2,
                        DataSingleton::Instance()->getPenSize()/2);
        break;
    }
    painter.setPen(Qt::black);
    painter.drawPoint(13, 13);
    painter.drawPoint(13, 3);
    painter.drawPoint(13, 5);
    painter.drawPoint(13, 21);
    painter.drawPoint(13, 23);
    painter.drawPoint(3, 13);
    painter.drawPoint(5, 13);
    painter.drawPoint(21, 13);
    painter.drawPoint(23, 13);
    painter.setPen(Qt::white);
    painter.drawPoint(13, 12);
    painter.drawPoint(13, 14);
    painter.drawPoint(12, 13);
    painter.drawPoint(14, 13);
    painter.drawPoint(13, 4);
    painter.drawPoint(13, 6);
    painter.drawPoint(13, 20);
    painter.drawPoint(13, 22);
    painter.drawPoint(4, 13);
    painter.drawPoint(6, 13);
    painter.drawPoint(20, 13);
    painter.drawPoint(22, 13);
    painter.end();
}