void TruckMapWidget::paintEvent(QPaintEvent *evt) { Lock l(m_scaleFactorMutex); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); const double scaleMax = 5; const double scaleMin = 1e-4; const double offsetViewMaxFactor = 8; if (m_scaleFactor < scaleMin) { m_scaleFactor = scaleMin; } else if (m_scaleFactor > scaleMax) { m_scaleFactor = scaleMax; } // White background. painter.fillRect(evt->rect(), QBrush(Qt::white)); // Variables for displaying labels on the map. QString description; QPointF pt_description; QRectF rect_description; QFont fontSettings = this->font(); QPen pen; // Map coordinate system transformation according to DIN 70000: x = 12am, y = 9am --> m_rotation = +90 (http://www.isupia.de/download/Fahrdynamische%20Größen.pdf) QTransform transformationDIN70000; transformationDIN70000.translate(evt->rect().width() / 2, evt->rect().height() / 2); transformationDIN70000.scale(m_scaleFactor, -m_scaleFactor); transformationDIN70000.rotate(m_rotation); // Transformation into the regular coordinate system. QTransform transformationCartesianCoordinateSystem; transformationCartesianCoordinateSystem.translate(evt->rect().width() / 2, evt->rect().height() / 2); transformationCartesianCoordinateSystem.scale(m_scaleFactor, -m_scaleFactor); transformationCartesianCoordinateSystem.rotate(m_rotation - 90); // Transformation into the regular coordinate system for descriptions. QTransform transformationCartesianCoordinateSystemForDescriptions; transformationCartesianCoordinateSystemForDescriptions.translate(evt->rect().width() / 2, evt->rect().height() / 2); transformationCartesianCoordinateSystemForDescriptions.scale(1, 1); transformationCartesianCoordinateSystemForDescriptions.rotate(m_rotation - 90); // Transformation for descriptions label in image coordinates. QTransform descriptionTrans; descriptionTrans.translate(0, 0); descriptionTrans.scale(1, 1); descriptionTrans.rotate(0); // Setup fonts. fontSettings.setPointSize(10); painter.setFont(fontSettings); // Setup axes parameters. const double scaleMultiplier = ceil((1 / ((m_scaleFactor * 100) / 50))); const double step = 100 * scaleMultiplier; const double zeroAxisWidth = 3; const QColor zeroAxisColor = Qt::black; const QColor gridAxisColor = Qt::gray; const QColor textColor = QPalette::Foreground; const double xStepFact = ceil(width() * offsetViewMaxFactor / step / m_scaleFactor); const double yStepFact = ceil(height() * offsetViewMaxFactor / step / m_scaleFactor); // Draw X-axes. for (double i = -yStepFact * step;i < yStepFact * step;i += step) { if ((int)(i / step) % 2) { painter.setPen(gridAxisColor); } else { description.sprintf("%.0f", i/1000.0); pt_description.setY(i); painter.setTransform(descriptionTrans); pt_description = transformationCartesianCoordinateSystem.map(pt_description); pt_description.setX(10); pt_description.setY(pt_description.y() - 5); painter.setPen(QPen(textColor)); painter.drawText(pt_description, description); if (fabs(i) < 1e-5) { pen.setWidthF(zeroAxisWidth / m_scaleFactor); pen.setColor(zeroAxisColor); } else { pen.setWidth(0); } painter.setPen(pen); } painter.setTransform(transformationDIN70000); painter.drawLine(-xStepFact * step, i, xStepFact * step, i); } // Draw Y-axis segments for (double i = -xStepFact * step;i < xStepFact * step;i += step) { if ((int)(i / step) % 2) { painter.setPen(gridAxisColor); } else { description.sprintf("%.0f", i/1000.0*-1); pt_description.setX(i); pt_description.setY(0); painter.setTransform(descriptionTrans); pt_description = transformationCartesianCoordinateSystem.map(pt_description); pt_description.setX(pt_description.x() + 5); pt_description.setY(height() - 10); painter.setPen(QPen(textColor)); painter.drawText(pt_description, description); if (fabs(i) < 1e-5) { pen.setWidthF(zeroAxisWidth / m_scaleFactor); pen.setColor(zeroAxisColor); } else { pen.setWidth(0); } painter.setPen(pen); } painter.setTransform(transformationDIN70000); painter.drawLine(i, -yStepFact * step, i, yStepFact * step); } // Draw objects. { Lock l2(m_objectsMutex); TimeStamp now; TimeStamp validUntil = m_environment.getValidUntil(); if((validUntil-now).toMicroseconds() > 0){ std::vector<from::opendlv::perception::Object> objectList = m_environment.getListOfObjects(); auto it = objectList.begin(); while (it != objectList.end()){ from::opendlv::perception::Object obj = *it; from::opendlv::model::Direction dir = obj.getDirection(); Point3 measurementPoint(obj.getDistance(), 0, 0); measurementPoint.rotateZ(dir.getAzimuth()); int _width = 200 * (m_scaleFactor * 300); int _height = 200 * (m_scaleFactor * 300); painter.setTransform(transformationDIN70000); painter.fillRect(measurementPoint.getX() * 1000,measurementPoint.getY() * 1000, _width, _height, QBrush(Qt::red)); { const QColor objInfoColor = Qt::black; pen.setColor(objInfoColor); pt_description.setX(measurementPoint.getX() * 1000); pt_description.setY(measurementPoint.getY() * 1000); pt_description = transformationDIN70000.map(pt_description); painter.setTransform(descriptionTrans); painter.setPen(pen); fontSettings.setPointSize(10); painter.setFont(fontSettings); stringstream sstr; sstr << "Id=" << obj.getObjectId() << ", d=" << obj.getDistance() << "m."; const string s = sstr.str(); description = s.c_str(); painter.drawText(pt_description, description); } it++; } } } // Draw axes labels. pen.setColor(zeroAxisColor); painter.setPen(pen); painter.setTransform(descriptionTrans); fontSettings.setPointSize(10); painter.setFont(fontSettings); description = "x [m]"; painter.drawText(evt->rect().width() / 2 + 15, 15, description); description = "y [m]"; painter.drawText(15, evt->rect().height() / 2 + 15, description); // Arrows for the axes. pen.setWidthF(zeroAxisWidth); pen.setColor(zeroAxisColor); painter.setPen(pen); // Arrow X axis. painter.drawLine(evt->rect().width() / 2, 0, evt->rect().width() / 2 - 15, 15); painter.drawLine(evt->rect().width() / 2, 0, evt->rect().width() / 2 + 15, 15); // Arrow Y axis. painter.drawLine(0, evt->rect().height() / 2, 15, evt->rect().height() / 2 - 15); painter.drawLine(0, evt->rect().height() / 2, 15, evt->rect().height() / 2 + 15); painter.end(); }
bool QgsEllipseSymbolLayerV2::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFactor, const QString& layerName, const QgsSymbolV2RenderContext* context, const QgsFeature* f, const QPointF& shift ) const { //width double symbolWidth = mSymbolWidth; QgsExpression* widthExpression = expression( "width" ); if ( widthExpression ) //1. priority: data defined setting on symbol layer level { symbolWidth = widthExpression->evaluate( const_cast<QgsFeature*>( f ) ).toDouble(); } else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolWidth = mSize; } if ( mSymbolWidthUnit == QgsSymbolV2::MM ) { symbolWidth *= mmMapUnitScaleFactor; } //height double symbolHeight = mSymbolHeight; QgsExpression* heightExpression = expression( "height" ); if ( heightExpression ) //1. priority: data defined setting on symbol layer level { symbolHeight = heightExpression->evaluate( const_cast<QgsFeature*>( f ) ).toDouble(); } else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolHeight = mSize; } if ( mSymbolHeightUnit == QgsSymbolV2::MM ) { symbolHeight *= mmMapUnitScaleFactor; } //outline width double outlineWidth = mOutlineWidth; QgsExpression* outlineWidthExpression = expression( "outline_width" ); if ( outlineWidthExpression ) { outlineWidth = outlineWidthExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toDouble(); } if ( mOutlineWidthUnit == QgsSymbolV2::MM ) { outlineWidth *= outlineWidth; } //fill color QColor fc = mFillColor; QgsExpression* fillColorExpression = expression( "fill_color" ); if ( fillColorExpression ) { fc = QColor( fillColorExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString() ); } int fillColorIndex = e.closestColorMatch( fc.rgb() ); //outline color QColor oc = mOutlineColor; QgsExpression* outlineColorExpression = expression( "outline_color" ); if ( outlineColorExpression ) { oc = QColor( outlineColorExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString() ); } int outlineColorIndex = e.closestColorMatch( oc.rgb() ); //symbol name QString symbolName = mSymbolName; QgsExpression* symbolNameExpression = expression( "symbol_name" ); if ( symbolNameExpression ) { QgsExpression* symbolNameExpression = expression( "symbol_name" ); symbolName = symbolNameExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString(); } //offset double offsetX = 0; double offsetY = 0; markerOffset( *context, offsetX, offsetY ); QPointF off( offsetX, offsetY ); //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle) double rotation = 0.0; QgsExpression* rotationExpression = expression( "rotation" ); if ( rotationExpression ) { rotation = rotationExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toDouble(); } else if ( !qgsDoubleNear( mAngle, 0.0 ) ) { rotation = mAngle; } rotation = -rotation; //rotation in Qt is counterclockwise if ( rotation ) off = _rotatedOffset( off, rotation ); QTransform t; t.translate( shift.x() + offsetX, shift.y() + offsetY ); if ( rotation != 0 ) t.rotate( rotation ); double halfWidth = symbolWidth / 2.0; double halfHeight = symbolHeight / 2.0; if ( symbolName == "circle" ) { if ( qgsDoubleNear( halfWidth, halfHeight ) ) { QPointF pt( t.map( QPointF( 0, 0 ) ) ); e.writeCircle( layerName, outlineColorIndex, QgsPoint( pt.x(), pt.y() ), halfWidth ); } else { QgsPolyline line; double stepsize = 2 * M_PI / 40; for ( int i = 0; i < 39; ++i ) { double angle = stepsize * i; double x = halfWidth * cos( angle ); double y = halfHeight * sin( angle ); QPointF pt( t.map( QPointF( x, y ) ) ); line.push_back( QgsPoint( pt.x(), pt.y() ) ); } //close ellipse with first point line.push_back( line.at( 0 ) ); e.writePolyline( line, layerName, "solid", outlineColorIndex, outlineWidth, true ); } } else if ( symbolName == "rectangle" ) { QPointF pt1( t.map( QPointF( -halfWidth, -halfHeight ) ) ); QPointF pt2( t.map( QPointF( halfWidth, -halfHeight ) ) ); QPointF pt3( t.map( QPointF( -halfWidth, halfHeight ) ) ); QPointF pt4( t.map( QPointF( halfWidth, halfHeight ) ) ); e.writeSolid( layerName, fillColorIndex, QgsPoint( pt1.x(), pt1.y() ), QgsPoint( pt2.x(), pt2.y() ), QgsPoint( pt3.x(), pt3.y() ), QgsPoint( pt4.x(), pt4.y() ) ); return true; } else if ( symbolName == "cross" ) { QgsPolyline line1( 2 ); QPointF pt1( t.map( QPointF( -halfWidth, 0 ) ) ); QPointF pt2( t.map( QPointF( halfWidth, 0 ) ) ); line1[0] = QgsPoint( pt1.x(), pt1.y() ); line1[1] = QgsPoint( pt2.x(), pt2.y() ); e.writePolyline( line1, layerName, "CONTINUOUS", outlineColorIndex, outlineWidth, false ); QgsPolyline line2( 2 ); QPointF pt3( t.map( QPointF( 0, halfHeight ) ) ); QPointF pt4( t.map( QPointF( 0, -halfHeight ) ) ); line2[0] = QgsPoint( pt3.x(), pt3.y() ); line2[1] = QgsPoint( pt4.x(), pt4.y() ); e.writePolyline( line2, layerName, "CONTINUOUS", outlineColorIndex, outlineWidth, false ); return true; } else if ( symbolName == "triangle" ) { QPointF pt1( t.map( QPointF( -halfWidth, -halfHeight ) ) ); QPointF pt2( t.map( QPointF( halfWidth, -halfHeight ) ) ); QPointF pt3( t.map( QPointF( 0, halfHeight ) ) ); QPointF pt4( t.map( QPointF( 0, halfHeight ) ) ); e.writeSolid( layerName, fillColorIndex, QgsPoint( pt1.x(), pt1.y() ), QgsPoint( pt2.x(), pt2.y() ), QgsPoint( pt3.x(), pt3.y() ), QgsPoint( pt4.x(), pt4.y() ) ); return true; } return false; //soon... }
bool PathStrokerPlugin::run(ScribusDoc* doc, QString) { ScribusDoc* currDoc = doc; if (currDoc == 0) currDoc = ScCore->primaryMainWindow()->doc; if (currDoc->m_Selection->count() > 0) { QVector<double> m_array; PageItem *currItem = currDoc->m_Selection->itemAt(0); FPointArray path = currItem->PoLine; QPainterPath pp; if (currItem->itemType() == PageItem::PolyLine) pp = path.toQPainterPath(false); else pp = path.toQPainterPath(true); if (currItem->NamedLStyle.isEmpty()) { QPainterPathStroker stroke; stroke.setCapStyle(currItem->lineEnd()); stroke.setJoinStyle(currItem->lineJoin()); if (currItem->lineStyle() == Qt::SolidLine) stroke.setDashPattern(currItem->lineStyle()); else { getDashArray(currItem->lineStyle(), 1, m_array); stroke.setDashPattern(m_array); } stroke.setWidth(currItem->lineWidth()); QPainterPath result = stroke.createStroke(pp).simplified(); if (currItem->startArrowIndex() != 0) { FPoint Start = currItem->PoLine.point(0); for (uint xx = 1; xx < currItem->PoLine.size(); xx += 2) { FPoint Vector = currItem->PoLine.point(xx); if ((Start.x() != Vector.x()) || (Start.y() != Vector.y())) { double r = atan2(Start.y()-Vector.y(),Start.x()-Vector.x())*(180.0/M_PI); QTransform arrowTrans; FPointArray arrow = currDoc->arrowStyles.at(currItem->startArrowIndex()-1).points.copy(); arrowTrans.translate(Start.x(), Start.y()); arrowTrans.rotate(r); arrowTrans.scale(currItem->lineWidth(), currItem->lineWidth()); arrow.map(arrowTrans); result.addPath(arrow.toQPainterPath(true)); break; } } } if (currItem->endArrowIndex() != 0) { FPoint End = currItem->PoLine.point(currItem->PoLine.size()-2); for (uint xx = currItem->PoLine.size()-1; xx > 0; xx -= 2) { FPoint Vector = currItem->PoLine.point(xx); if ((End.x() != Vector.x()) || (End.y() != Vector.y())) { double r = atan2(End.y()-Vector.y(),End.x()-Vector.x())*(180.0/M_PI); QTransform arrowTrans; FPointArray arrow = currDoc->arrowStyles.at(currItem->endArrowIndex()-1).points.copy(); arrowTrans.translate(End.x(), End.y()); arrowTrans.rotate(r); arrowTrans.scale(currItem->lineWidth(), currItem->lineWidth()); arrow.map(arrowTrans); result.addPath(arrow.toQPainterPath(true)); break; } } } currDoc->m_Selection->clear(); PageItem* newItem = currDoc->convertItemTo(currItem, PageItem::Polygon); newItem->setLineWidth(0); newItem->setLineStyle(Qt::SolidLine); newItem->setFillColor(newItem->lineColor()); newItem->setFillShade(newItem->lineShade()); newItem->setFillTransparency(newItem->lineTransparency()); newItem->setFillBlendmode(newItem->lineBlendmode()); FPointArray points; points.fromQPainterPath(result); newItem->PoLine = points; newItem->Frame = false; newItem->ClipEdited = true; newItem->FrameType = 3; currDoc->AdjustItemSize(newItem); newItem->OldB2 = newItem->width(); newItem->OldH2 = newItem->height(); newItem->updateClip(); newItem->ContourLine = newItem->PoLine.copy(); newItem->setFillEvenOdd(true); currDoc->m_Selection->addItem(newItem); } else { currDoc->m_Selection->clear(); multiLine ml = currDoc->MLineStyles[currItem->NamedLStyle]; bool first = true; for (int it = ml.size()-1; it > -1; it--) { if ((ml[it].Color != CommonStrings::None) && (ml[it].Width != 0)) { QPainterPathStroker stroke; stroke.setCapStyle(static_cast<Qt::PenCapStyle>(ml[it].LineEnd)); stroke.setJoinStyle(static_cast<Qt::PenJoinStyle>(ml[it].LineJoin)); if (static_cast<Qt::PenStyle>(ml[it].Dash) == Qt::SolidLine) stroke.setDashPattern(static_cast<Qt::PenStyle>(ml[it].Dash)); else { getDashArray(static_cast<Qt::PenStyle>(ml[it].Dash), 1, m_array); stroke.setDashPattern(m_array); } stroke.setWidth(ml[it].Width); QPainterPath result = stroke.createStroke(pp).simplified(); PageItem* newItem; if (first) { newItem = currDoc->convertItemTo(currItem, PageItem::Polygon); } else { newItem = new PageItem_Polygon(*currItem); newItem->convertTo(PageItem::Polygon); currDoc->Items->append(newItem); } first = false; newItem->ItemNr = currDoc->Items->count()-1; newItem->setLineStyle(Qt::SolidLine); newItem->setFillColor(ml[it].Color); newItem->setFillShade(ml[it].Shade); newItem->setFillTransparency(newItem->lineTransparency()); newItem->setFillBlendmode(newItem->lineBlendmode()); newItem->setLineColor(CommonStrings::None); newItem->setCustomLineStyle(""); FPointArray points; points.fromQPainterPath(result); newItem->PoLine = points; newItem->Frame = false; newItem->ClipEdited = true; newItem->FrameType = 3; currDoc->AdjustItemSize(newItem); newItem->OldB2 = newItem->width(); newItem->OldH2 = newItem->height(); newItem->updateClip(); newItem->ContourLine = newItem->PoLine.copy(); newItem->setFillEvenOdd(true); currDoc->m_Selection->addItem(newItem); } } if (currItem->startArrowIndex() != 0) { FPoint Start = currItem->PoLine.point(0); for (uint xx = 1; xx < currItem->PoLine.size(); xx += 2) { FPoint Vector = currItem->PoLine.point(xx); if ((Start.x() != Vector.x()) || (Start.y() != Vector.y())) { double r = atan2(Start.y()-Vector.y(),Start.x()-Vector.x())*(180.0/M_PI); QTransform arrowTrans; FPointArray arrow = currDoc->arrowStyles.at(currItem->startArrowIndex()-1).points.copy(); arrowTrans.translate(Start.x(), Start.y()); arrowTrans.rotate(r); arrowTrans.scale(currItem->lineWidth(), currItem->lineWidth()); arrow.map(arrowTrans); PageItem* newItem = new PageItem_Polygon(*currItem); currDoc->Items->append(newItem); newItem->ItemNr = currDoc->Items->count()-1; newItem->setLineWidth(0); newItem->setLineStyle(Qt::SolidLine); newItem->setCustomLineStyle(""); newItem->setFillColor(newItem->lineColor()); newItem->setFillShade(newItem->lineShade()); newItem->setFillTransparency(newItem->lineTransparency()); newItem->setFillBlendmode(newItem->lineBlendmode()); newItem->PoLine = arrow; newItem->Frame = false; newItem->ClipEdited = true; newItem->FrameType = 3; currDoc->AdjustItemSize(newItem); newItem->OldB2 = newItem->width(); newItem->OldH2 = newItem->height(); newItem->updateClip(); newItem->ContourLine = newItem->PoLine.copy(); newItem->setFillEvenOdd(true); currDoc->m_Selection->addItem(newItem); break; } } } if (currItem->endArrowIndex() != 0) { FPoint End = currItem->PoLine.point(currItem->PoLine.size()-2); for (uint xx = currItem->PoLine.size()-1; xx > 0; xx -= 2) { FPoint Vector = currItem->PoLine.point(xx); if ((End.x() != Vector.x()) || (End.y() != Vector.y())) { double r = atan2(End.y()-Vector.y(),End.x()-Vector.x())*(180.0/M_PI); QTransform arrowTrans; FPointArray arrow = currDoc->arrowStyles.at(currItem->endArrowIndex()-1).points.copy(); arrowTrans.translate(End.x(), End.y()); arrowTrans.rotate(r); arrowTrans.scale(currItem->lineWidth(), currItem->lineWidth()); arrow.map(arrowTrans); PageItem* newItem = new PageItem_Polygon(*currItem); currDoc->Items->append(newItem); newItem->ItemNr = currDoc->Items->count()-1; newItem->setLineWidth(0); newItem->setLineStyle(Qt::SolidLine); newItem->setCustomLineStyle(""); newItem->setFillColor(newItem->lineColor()); newItem->setFillShade(newItem->lineShade()); newItem->setFillTransparency(newItem->lineTransparency()); newItem->setFillBlendmode(newItem->lineBlendmode()); newItem->PoLine = arrow; newItem->Frame = false; newItem->ClipEdited = true; newItem->FrameType = 3; currDoc->AdjustItemSize(newItem); newItem->OldB2 = newItem->width(); newItem->OldH2 = newItem->height(); newItem->updateClip(); newItem->ContourLine = newItem->PoLine.copy(); newItem->setFillEvenOdd(true); currDoc->m_Selection->addItem(newItem); break; } } } if (currDoc->m_Selection->count() > 1) currDoc->itemSelection_GroupObjects(false, false); currDoc->m_Selection->itemAt(0)->emitAllToGUI(); } currDoc->changed(); } return true; }
bool QgsEllipseSymbolLayerV2::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFactor, const QString& layerName, const QgsSymbolV2RenderContext* context, const QgsFeature* f, const QPointF& shift ) const { //width double symbolWidth = mSymbolWidth; if ( hasDataDefinedProperty( "width" ) ) //1. priority: data defined setting on symbol layer le { symbolWidth = evaluateDataDefinedProperty( "width", f, mSymbolWidth ).toDouble(); } else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolWidth = mSize; } if ( mSymbolWidthUnit == QgsSymbolV2::MM ) { symbolWidth *= mmMapUnitScaleFactor; } //height double symbolHeight = mSymbolHeight; if ( hasDataDefinedProperty( "height" ) ) //1. priority: data defined setting on symbol layer level { symbolHeight = evaluateDataDefinedProperty( "height", f, mSymbolHeight ).toDouble(); } else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolHeight = mSize; } if ( mSymbolHeightUnit == QgsSymbolV2::MM ) { symbolHeight *= mmMapUnitScaleFactor; } //outline width double outlineWidth = mOutlineWidth; if ( hasDataDefinedProperty( "outline_width" ) ) { outlineWidth = evaluateDataDefinedProperty( "outline_width", f, mOutlineWidth ).toDouble(); } if ( mOutlineWidthUnit == QgsSymbolV2::MM ) { outlineWidth *= outlineWidth; } //fill color bool ok; QColor fc = mFillColor; if ( hasDataDefinedProperty( "fill_color" ) ) { QString colorString = evaluateDataDefinedProperty( "fill_color", f, QVariant(), &ok ).toString(); if ( ok ) fc = QColor( colorString ); } //outline color QColor oc = mOutlineColor; if ( hasDataDefinedProperty( "outline_color" ) ) { QString colorString = evaluateDataDefinedProperty( "outline_color", f, QVariant(), &ok ).toString(); if ( ok ) oc = QColor( colorString ); } //symbol name QString symbolName = mSymbolName; if ( hasDataDefinedProperty( "symbol_name" ) ) { symbolName = evaluateDataDefinedProperty( "symbol_name", f, mSymbolName ).toString(); } //offset double offsetX = 0; double offsetY = 0; markerOffset( *context, offsetX, offsetY ); QPointF off( offsetX, offsetY ); //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle) double rotation = 0.0; if ( hasDataDefinedProperty( "rotation" ) ) { rotation = evaluateDataDefinedProperty( "rotation", f, mAngle ).toDouble(); } else if ( !qgsDoubleNear( mAngle, 0.0 ) ) { rotation = mAngle; } rotation = -rotation; //rotation in Qt is counterclockwise if ( rotation ) off = _rotatedOffset( off, rotation ); QTransform t; t.translate( shift.x() + offsetX, shift.y() + offsetY ); if ( rotation != 0 ) t.rotate( rotation ); double halfWidth = symbolWidth / 2.0; double halfHeight = symbolHeight / 2.0; if ( symbolName == "circle" ) { if ( qgsDoubleNear( halfWidth, halfHeight ) ) { QPointF pt( t.map( QPointF( 0, 0 ) ) ); e.writeFilledCircle( layerName, oc, pt, halfWidth ); } else { QgsPolyline line; double stepsize = 2 * M_PI / 40; for ( int i = 0; i < 39; ++i ) { double angle = stepsize * i; double x = halfWidth * cos( angle ); double y = halfHeight * sin( angle ); QPointF pt( t.map( QPointF( x, y ) ) ); line.push_back( pt ); } //close ellipse with first point line.push_back( line.at( 0 ) ); e.writePolyline( line, layerName, "SOLID", oc, outlineWidth ); } } else if ( symbolName == "rectangle" ) { QPointF pt1( t.map( QPointF( -halfWidth, -halfHeight ) ) ); QPointF pt2( t.map( QPointF( halfWidth, -halfHeight ) ) ); QPointF pt3( t.map( QPointF( -halfWidth, halfHeight ) ) ); QPointF pt4( t.map( QPointF( halfWidth, halfHeight ) ) ); e.writeSolid( layerName, fc, pt1, pt2, pt3, pt4 ); return true; } else if ( symbolName == "cross" ) { QgsPolyline line1( 2 ); QPointF pt1( t.map( QPointF( -halfWidth, 0 ) ) ); QPointF pt2( t.map( QPointF( halfWidth, 0 ) ) ); line1[0] = pt1; line1[1] = pt2; e.writePolyline( line1, layerName, "CONTINUOUS", oc, outlineWidth ); QgsPolyline line2( 2 ); QPointF pt3( t.map( QPointF( 0, halfHeight ) ) ); QPointF pt4( t.map( QPointF( 0, -halfHeight ) ) ); line2[0] = pt3; line2[1] = pt4; e.writePolyline( line2, layerName, "CONTINUOUS", oc, outlineWidth ); return true; } else if ( symbolName == "triangle" ) { QPointF pt1( t.map( QPointF( -halfWidth, -halfHeight ) ) ); QPointF pt2( t.map( QPointF( halfWidth, -halfHeight ) ) ); QPointF pt3( t.map( QPointF( 0, halfHeight ) ) ); QPointF pt4( t.map( QPointF( 0, halfHeight ) ) ); e.writeSolid( layerName, fc, pt1, pt2, pt3, pt4 ); return true; } return false; //soon... }
void IsometricRenderer::drawMapObject(QPainter *painter, const MapObject *object, const QColor &color) const { painter->save(); QPen pen(Qt::black); if (object->tile()) { const QPixmap &img = object->tile()->image(); QPointF paintOrigin(-img.width() / 2, -img.height()); paintOrigin += tileToPixelCoords(object->position()).toPoint(); painter->drawPixmap(paintOrigin, img); const QFontMetrics fm = painter->fontMetrics(); QString name = fm.elidedText(object->name(), Qt::ElideRight, img.width() + 2); if (!name.isEmpty()) painter->drawText(QPoint(paintOrigin.x(), paintOrigin.y() - 5 + 1), name); pen.setStyle(Qt::SolidLine); painter->setPen(pen); painter->drawRect(QRectF(paintOrigin, img.size())); pen.setStyle(Qt::DotLine); pen.setColor(color); painter->setPen(pen); painter->drawRect(QRectF(paintOrigin, img.size())); if (!name.isEmpty()) painter->drawText(QPoint(paintOrigin.x(), paintOrigin.y() - 5), name); } else { QColor brushColor = color; brushColor.setAlpha(50); QBrush brush(brushColor); pen.setJoinStyle(Qt::RoundJoin); pen.setCapStyle(Qt::RoundCap); pen.setWidth(2); painter->setPen(pen); painter->setRenderHint(QPainter::Antialiasing); // TODO: Draw the object name // TODO: Do something sensible to make null-sized objects usable switch (object->shape()) { case MapObject::Ellipse: { QPointF topLeft(tileToPixelCoords(object->bounds().topLeft())); QPointF bottomLeft(tileToPixelCoords(object->bounds().bottomLeft())); QPointF topRight(tileToPixelCoords(object->bounds().topRight())); const qreal headerX = bottomLeft.x(); const qreal headerY = topLeft.y(); QRectF rect(bottomLeft, topRight); const QFontMetrics fm = painter->fontMetrics(); QString name = fm.elidedText(object->name(), Qt::ElideRight, rect.width() + 2); QPolygonF polygon = tileRectToPolygon(object->bounds()); float tw = map()->tileWidth(); float th = map()->tileHeight(); QPointF transformScale(1, 1); if (tw > th) transformScale = QPointF(1, th/tw); else transformScale = QPointF(tw/th, 1); QPointF l1 = polygon.at(1) - polygon.at(0); QPointF l2 = polygon.at(3) - polygon.at(0); QTransform trans; trans.scale(transformScale.x(), transformScale.y()); trans.rotate(45); QTransform iTrans = trans.inverted(); QPointF l1x = iTrans.map(l1); QPointF l2x = iTrans.map(l2); QSizeF ellipseSize(l1x.manhattanLength(), l2x.manhattanLength()); painter->save(); painter->setPen(pen); painter->translate(polygon.at(0)); painter->scale(transformScale.x(), transformScale.y()); painter->rotate(45); painter->drawEllipse(QRectF(QPointF(0, 0), ellipseSize)); painter->restore(); painter->setBrush(Qt::NoBrush); painter->drawPolygon(polygon); if (!name.isEmpty()) painter->drawText(QPoint(headerX, headerY - 5), name); pen.setColor(color); painter->setPen(pen); painter->setBrush(Qt::NoBrush); painter->translate(QPointF(0, -1)); painter->drawPolygon(polygon); painter->setBrush(brush); painter->save(); painter->translate(polygon.at(0)); painter->scale(transformScale.x(), transformScale.y()); painter->rotate(45); painter->drawEllipse(QRectF(QPointF(0, 0), ellipseSize)); painter->restore(); if (!name.isEmpty()) painter->drawText(QPoint(headerX, headerY - 5), name); break; } case MapObject::Rectangle: { QPointF topLeft(tileToPixelCoords(object->bounds().topLeft())); QPointF bottomLeft(tileToPixelCoords(object->bounds().bottomLeft())); QPointF topRight(tileToPixelCoords(object->bounds().topRight())); const qreal headerX = bottomLeft.x(); const qreal headerY = topLeft.y(); QRectF rect(bottomLeft, topRight); const QFontMetrics fm = painter->fontMetrics(); QString name = fm.elidedText(object->name(), Qt::ElideRight, rect.width() + 2); QPolygonF polygon = tileRectToPolygon(object->bounds()); painter->drawPolygon(polygon); if (!name.isEmpty()) painter->drawText(QPoint(headerX, headerY - 5 + 1), name); pen.setColor(color); painter->setPen(pen); painter->setBrush(brush); polygon.translate(0, -1); painter->drawPolygon(polygon); if (!name.isEmpty()) painter->drawText(QPoint(headerX, headerY - 5), name); break; } case MapObject::Polygon: { const QPointF &pos = object->position(); const QPolygonF polygon = object->polygon().translated(pos); QPolygonF screenPolygon = tileToPixelCoords(polygon); const QRectF polygonBoundingRect = screenPolygon.boundingRect(); const QFontMetrics fm = painter->fontMetrics(); QString name = fm.elidedText(object->name(), Qt::ElideRight, polygonBoundingRect.width() + 2); if (!name.isEmpty()) painter->drawText(QPoint(polygonBoundingRect.left(), polygonBoundingRect.top() - 5 + 1), name); painter->drawPolygon(screenPolygon); pen.setColor(color); painter->setPen(pen); painter->setBrush(brush); screenPolygon.translate(0, -1); painter->drawPolygon(screenPolygon); if (!name.isEmpty()) painter->drawText(QPoint(polygonBoundingRect.left(), polygonBoundingRect.top() - 5), name); break; } case MapObject::Polyline: { const QPointF &pos = object->position(); const QPolygonF polygon = object->polygon().translated(pos); QPolygonF screenPolygon = tileToPixelCoords(polygon); painter->drawPolyline(screenPolygon); pen.setColor(color); painter->setPen(pen); screenPolygon.translate(0, -1); painter->drawPolyline(screenPolygon); break; } } } painter->restore(); }
bool RawIOHandler::read(QImage *image) { if (!d->load(device())) return false; QSize finalSize = d->scaledSize.isValid() ? d->scaledSize : d->defaultSize; const libraw_data_t &imgdata = d->raw->imgdata; libraw_processed_image_t *output; if (finalSize.width() < imgdata.thumbnail.twidth || finalSize.height() < imgdata.thumbnail.theight) { qDebug() << "Using thumbnail"; d->raw->unpack_thumb(); output = d->raw->dcraw_make_mem_thumb(); } else { qDebug() << "Decoding raw data"; d->raw->unpack(); d->raw->dcraw_process(); output = d->raw->dcraw_make_mem_image(); } QImage unscaled; uchar *pixels = 0; if (output->type == LIBRAW_IMAGE_JPEG) { unscaled.loadFromData(output->data, output->data_size, "JPEG"); if (imgdata.sizes.flip != 0) { QTransform rotation; int angle = 0; if (imgdata.sizes.flip == 3) angle = 180; else if (imgdata.sizes.flip == 5) angle = -90; else if (imgdata.sizes.flip == 6) angle = 90; if (angle != 0) { rotation.rotate(angle); unscaled = unscaled.transformed(rotation); } } } else { int numPixels = output->width * output->height; int colorSize = output->bits / 8; int pixelSize = output->colors * colorSize; pixels = new uchar[numPixels * 4]; uchar *data = output->data; for (int i = 0; i < numPixels; i++, data += pixelSize) { if (output->colors == 3) { pixels[i * 4] = data[2 * colorSize]; pixels[i * 4 + 1] = data[1 * colorSize]; pixels[i * 4 + 2] = data[0]; } else { pixels[i * 4] = data[0]; pixels[i * 4 + 1] = data[0]; pixels[i * 4 + 2] = data[0]; } } unscaled = QImage(pixels, output->width, output->height, QImage::Format_RGB32); } if (unscaled.size() != finalSize) { // TODO: use quality parameter to decide transformation method *image = unscaled.scaled(finalSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } else { *image = unscaled; if (output->type == LIBRAW_IMAGE_BITMAP) { // make sure that the bits are copied uchar *b = image->bits(); Q_UNUSED(b); } } d->raw->dcraw_clear_mem(output); delete pixels; return true; }
void CubemapEditorDialog::SaveCubemap(const QString& path) { FilePath filePath(path.toStdString()); DAVA::uint8 faceMask = GetFaceMask(); //copy file to the location where .tex will be put. Add suffixes to file names to distinguish faces String fileNameWithoutExtension = filePath.GetFilename(); String extension = filePath.GetExtension(); fileNameWithoutExtension.replace(fileNameWithoutExtension.find(extension), extension.size(), ""); for(int i = 0 ; i < CubemapUtils::GetMaxFaces(); ++i) { if(!facePath[i].isNull()) { FilePath faceFilePath = filePath; faceFilePath.ReplaceFilename(fileNameWithoutExtension + CubemapUtils::GetFaceNameSuffix(CubemapUtils::MapUIToFrameworkFace(i)) + "." + CubemapUtils::GetDefaultFaceExtension()); DAVA::String targetFullPath = faceFilePath.GetAbsolutePathname().c_str(); if(facePath[i] != targetFullPath.c_str()) { if(QFile::exists(targetFullPath.c_str())) { int answer = ShowQuestion("File overwrite", "File " + targetFullPath + " already exist. Do you want to overwrite it with " + facePath[i].toStdString(), MB_FLAG_YES | MB_FLAG_NO, MB_FLAG_NO); if(MB_FLAG_YES == answer) { bool removeResult = QFile::remove(targetFullPath.c_str()); if(!removeResult) { ShowErrorDialog("Failed to copy texture " + facePath[i].toStdString() + " to " + targetFullPath.c_str()); return; } } else { continue; } } bool copyResult = QFile::copy(facePath[i], targetFullPath.c_str()); if(!copyResult) { ShowErrorDialog("Failed to copy texture " + facePath[i].toStdString() + " to " + targetFullPath); return; } } ClickableQLabel* faceLabel = GetLabelForFace(i); if(faceLabel->GetRotation() != 0) { QTransform transform; transform.rotate(faceLabel->GetRotation()); QImage qimg(targetFullPath.c_str()); QImage rotatedImage = qimg.transformed(transform); rotatedImage.save(targetFullPath.c_str()); faceLabel->SetRotation(0); } } } TextureDescriptor* descriptor = new TextureDescriptor(); bool descriptorReady = false; if(filePath.Exists()) { descriptorReady = descriptor->Load(filePath); } if(!descriptorReady) { descriptor->SetDefaultValues(); descriptor->drawSettings.wrapModeS = descriptor->drawSettings.wrapModeT = Texture::WRAP_CLAMP_TO_EDGE; } descriptor->dataSettings.faceDescription = faceMask; descriptor->Save(filePath); SafeDelete(descriptor); QMessageBox::information(this, "Cubemap texture save result", "Cubemap texture was saved successfully!"); }
void ImagePane::paintEvent(QPaintEvent* /*event*/) { QPainter painter(this); //draw the transformed version of the text-object image painter.drawImage(0, 0, transformedImage); //then we draw the bounding boxes //TODO inscriptions with at least one graph are a different color (?) //in case index numbers are visible, set font QFont font; font.setPixelSize(30/zoom); //TODO make font size dependent on resolution painter.setFont(font); QPen pen; pen.setWidth(0); pen.setColor(Qt::red); painter.setPen(pen); //make a list of bounding boxes according to current mode BoxList currentBoxList; //this is a list of all boxes currentBoxList.clear(); switch(mode) { case SURFACE: currentBoxList.append(*surf); //list of one item, consting of the surface bounding box break; case INSCRIPTION: for(int i=0; i < surf->inscriptionCount(); i++) currentBoxList.insertBox(surf->inscrAt(i), i); break; case GRAPH: for(int i=0; i < surf->ptrInscrAt(currentInscrIndex)->count(); i++) currentBoxList.insertBox(surf->ptrInscrAt(currentInscrIndex)->at(i), i); break; default: break; } //iterate through the list of bounding boxes for (int i=0; i<currentBoxList.size(); i++) { BoundingBox currentBox = currentBoxList.at(i); //the bounding boxes need to be rotated and scaled QTransform boxTransform; //identity matrix //first we need to handle the bounding box's own rotation //by inverting the true matrix that was applied to the image //at the time each bounding box was created //(note: we don't need to worry about scale, as we took account of that //when the bounding box was created) boxTransform.rotate(currentBox.getRotation()); boxTransform = QImage::trueMatrix(boxTransform, currentImage.width(), currentImage.height()); boxTransform = boxTransform.inverted(); //then we compound the above matrix with the current transformation of the image QTransform imageTrueTransform = QImage::trueMatrix(transform, currentImage.width(), currentImage.height()); painter.setWorldTransform(boxTransform * imageTrueTransform); //now draw the box //pen color is red; set the pen-color to green if this is the current box. if(i==currentBoxIndex) { QPen pen; pen.setWidth(0); pen.setColor(Qt::green); painter.setPen(pen); } painter.drawRect(currentBox); //and add an (optional) index number if(indexNumbersVisible) { painter.drawText(currentBox.left(), currentBox.top(), 50/zoom, 50/zoom, Qt::AlignBottom, QString("%1").arg(i+1)); //visible index, so base = 1, not zero } //return pen color to red (might be green) QPen pen; pen.setWidth(0); pen.setColor(Qt::red); painter.setPen(Qt::red); } //if label is not resized, it will stay large on zoom out //resulting in misleading / redundant scroll bars resize(transformedImage.size()); // keep label same size as image }
void PageItem_Spiral::getVisualBoundingRect(double * x1, double * y1, double * x2, double * y2) const { PageItem::getVisualBoundingRect(x1, y1, x2, y2); QRectF totalRect(QPointF(*x1, *y1), QPointF(*x2, *y2)); if (m_startArrowIndex != 0 && !PoLine.empty()) { QTransform arrowTrans; FPointArray arrow = m_Doc->arrowStyles().at(m_startArrowIndex-1).points.copy(); arrowTrans.translate(m_xPos, m_yPos); arrowTrans.rotate(m_rotation); FPoint Start = PoLine.point(0); for (int xx = 1; xx < PoLine.size(); xx += 2) { FPoint Vector = PoLine.point(xx); if ((Start.x() != Vector.x()) || (Start.y() != Vector.y())) { arrowTrans.translate(Start.x(), Start.y()); arrowTrans.rotate(atan2(Start.y()-Vector.y(),Start.x()-Vector.x())*(180.0/M_PI)); arrowTrans.scale(m_startArrowScale / 100.0, m_startArrowScale / 100.0); if (NamedLStyle.isEmpty()) { if (m_lineWidth != 0.0) arrowTrans.scale(m_lineWidth, m_lineWidth); } else { multiLine ml = m_Doc->MLineStyles[NamedLStyle]; if (ml[ml.size()-1].Width != 0.0) arrowTrans.scale(ml[ml.size()-1].Width, ml[ml.size()-1].Width); } arrow.map(arrowTrans); break; } } FPoint minAr = getMinClipF(&arrow); FPoint maxAr = getMaxClipF(&arrow); totalRect = totalRect.united(QRectF(QPointF(minAr.x(), minAr.y()), QPointF(maxAr.x(), maxAr.y()))); } if (m_endArrowIndex != 0 && PoLine.size() >= 2) { QTransform arrowTrans; FPointArray arrow = m_Doc->arrowStyles().at(m_endArrowIndex-1).points.copy(); arrowTrans.translate(m_xPos, m_yPos); arrowTrans.rotate(m_rotation); FPoint End = PoLine.point(PoLine.size()-2); for (uint xx = PoLine.size()-1; xx > 0; xx -= 2) { FPoint Vector = PoLine.point(xx); if ((End.x() != Vector.x()) || (End.y() != Vector.y())) { arrowTrans.translate(End.x(), End.y()); arrowTrans.rotate(atan2(End.y()-Vector.y(),End.x()-Vector.x())*(180.0/M_PI)); arrowTrans.scale(m_endArrowScale / 100.0, m_endArrowScale / 100.0); if (NamedLStyle.isEmpty()) { if (m_lineWidth != 0.0) arrowTrans.scale(m_lineWidth, m_lineWidth); } else { multiLine ml = m_Doc->MLineStyles[NamedLStyle]; if (ml[ml.size()-1].Width != 0.0) arrowTrans.scale(ml[ml.size()-1].Width, ml[ml.size()-1].Width); } arrow.map(arrowTrans); break; } } FPoint minAr = getMinClipF(&arrow); FPoint maxAr = getMaxClipF(&arrow); totalRect = totalRect.united(QRectF(QPointF(minAr.x(), minAr.y()), QPointF(maxAr.x(), maxAr.y()))); } totalRect.getCoords(x1, y1, x2, y2); }
void BI_FootprintPad::updateGraphicsItemTransform() noexcept { QTransform t; if (mFootprint.getIsMirrored()) t.scale(qreal(-1), qreal(1)); t.rotate(-mRotation.toDeg()); mGraphicsItem->setTransform(t); }
void CanvasMode_Rotate::getNewItemPosition(PageItem* item, FPoint& pos, double& rotation) { double newAngle = xy2Deg(m_canvasCurrCoord.x() - m_rotCenter.x(), m_canvasCurrCoord.y() - m_rotCenter.y()); if (m_angleConstrained) { newAngle = constrainAngle(newAngle, m_doc->opToolPrefs().constrain); /*double oldAngle = constrainAngle(m_startAngle, m_doc->opToolPrefs.constrain); newAngle = m_doc->m_Selection->isMultipleSelection() ? (newAngle - oldAngle) : newAngle;*/ m_view->oldW = constrainAngle(m_view->oldW, m_doc->opToolPrefs().constrain); newAngle = m_doc->m_Selection->isMultipleSelection() ? (newAngle - m_view->oldW) : newAngle; } else if (m_doc->m_Selection->isMultipleSelection()) newAngle = (newAngle - m_startAngle); else newAngle = item->rotation() - (m_startAngle - newAngle); if (m_doc->m_Selection->isMultipleSelection()) { QTransform ma; ma.translate(m_rotCenter.x(), m_rotCenter.y()); ma.scale(1, 1); ma.rotate(newAngle); FPoint n(item->xPos() - m_rotCenter.x(), item->yPos() - m_rotCenter.y()); pos.setXY(ma.m11() * n.x() + ma.m21() * n.y() + ma.dx(), ma.m22() * n.y() + ma.m12() * n.x() + ma.dy()); rotation = item->rotation() + newAngle; } else if (m_rotMode != 0) { FPoint n(0,0); QTransform ma; ma.translate(item->xPos(), item->yPos()); ma.scale(1, 1); ma.rotate(item->rotation()); double ro = newAngle - item->rotation(); switch (m_rotMode) { case 2: ma.translate(item->width()/2.0, item->height()/2.0); n = FPoint(-item->width()/2.0, -item->height()/2.0); break; case 4: ma.translate(item->width(), item->height()); n = FPoint(-item->width(), -item->height()); break; case 3: ma.translate(0, item->height()); n = FPoint(0, -item->height()); break; case 1: ma.translate(item->width(), 0); n = FPoint(-item->width(), 0); break; } ma.rotate(ro); pos.setXY(ma.m11() * n.x() + ma.m21() * n.y() + ma.dx(), ma.m22() * n.y() + ma.m12() * n.x() + ma.dy()); rotation = newAngle; } else { pos.setXY(item->xPos(), item->yPos()); rotation = newAngle; } }
// This is called from the worker thread, not main thread bool LoadImageJob::run() { GFile* gfile = fm_path_to_gfile(path_); GFileInputStream* fileStream = g_file_read(gfile, cancellable_, &error_); g_object_unref(gfile); if(fileStream) { // if the file stream is successfually opened QBuffer imageBuffer; GInputStream* inputStream = G_INPUT_STREAM(fileStream); while(!g_cancellable_is_cancelled(cancellable_)) { char buffer[4096]; gssize readSize = g_input_stream_read(inputStream, buffer, 4096, cancellable_, &error_); if(readSize == -1 || readSize == 0) // error or EOF break; // append the bytes read to the image buffer imageBuffer.buffer().append(buffer, readSize); } g_input_stream_close(inputStream, NULL, NULL); // FIXME: maybe it's a better idea to implement a GInputStream based QIODevice. if(!error_ && !g_cancellable_is_cancelled(cancellable_)) { // load the image from buffer if there are no errors image_ = QImage::fromData(imageBuffer.buffer()); if(!image_.isNull()) { // if the image is loaded correctly // check if this file is a jpeg file // FIXME: can we use FmFileInfo instead if it's available? const char* basename = fm_path_get_basename(path_); char* mime_type = g_content_type_guess(basename, NULL, 0, NULL); if(mime_type && strcmp(mime_type, "image/jpeg") == 0) { // this is a jpeg file // use libexif to extract additional info embedded in jpeg files ExifLoader *exif_loader = exif_loader_new(); // write image data to exif loader exif_loader_write(exif_loader, (unsigned char*)imageBuffer.data().constData(), (unsigned int)imageBuffer.size()); ExifData *exif_data = exif_loader_get_data(exif_loader); exif_loader_unref(exif_loader); if(exif_data) { /* reference for EXIF orientation tag: * http://www.impulseadventure.com/photo/exif-orientation.html */ ExifEntry* orient_ent = exif_data_get_entry(exif_data, EXIF_TAG_ORIENTATION); if(orient_ent) { /* orientation flag found in EXIF */ gushort orient; ExifByteOrder bo = exif_data_get_byte_order(exif_data); /* bo == EXIF_BYTE_ORDER_INTEL ; */ orient = exif_get_short (orient_ent->data, bo); qreal rotate_degrees = 0.0; switch(orient) { case 1: /* no rotation */ break; case 8: rotate_degrees = 270.0; break; case 3: rotate_degrees = 180.0; break; case 6: rotate_degrees = 90.0; break; } // rotate the image according to EXIF orientation tag if(rotate_degrees != 0.0) { QTransform transform; transform.rotate(rotate_degrees); image_ = image_.transformed(transform, Qt::SmoothTransformation); } // TODO: handle other EXIF tags as well } exif_data_unref(exif_data); } } g_free(mime_type); } } } return false; }
bool QgsEllipseSymbolLayerV2::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFactor, const QString& layerName, QgsSymbolV2RenderContext &context, QPointF shift ) const { //width double symbolWidth = mSymbolWidth; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_WIDTH ) ) //1. priority: data defined setting on symbol layer le { context.setOriginalValueVariable( mSymbolWidth ); symbolWidth = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_WIDTH, context, mSymbolWidth ).toDouble(); } else if ( context.renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolWidth = mSize; } if ( mSymbolWidthUnit == QgsSymbolV2::MM ) { symbolWidth *= mmMapUnitScaleFactor; } //height double symbolHeight = mSymbolHeight; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_HEIGHT ) ) //1. priority: data defined setting on symbol layer level { context.setOriginalValueVariable( mSymbolHeight ); symbolHeight = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_HEIGHT, context, mSymbolHeight ).toDouble(); } else if ( context.renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level { symbolHeight = mSize; } if ( mSymbolHeightUnit == QgsSymbolV2::MM ) { symbolHeight *= mmMapUnitScaleFactor; } //outline width double outlineWidth = mOutlineWidth; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_WIDTH ) ) { context.setOriginalValueVariable( mOutlineWidth ); outlineWidth = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_WIDTH, context, mOutlineWidth ).toDouble(); } if ( mOutlineWidthUnit == QgsSymbolV2::MM ) { outlineWidth *= outlineWidth; } //fill color bool ok; QColor fc = mColor; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_FILL_COLOR ) ) { context.setOriginalValueVariable( QgsSymbolLayerV2Utils::encodeColor( mColor ) ); QString colorString = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_FILL_COLOR, context, QVariant(), &ok ).toString(); if ( ok ) fc = QgsSymbolLayerV2Utils::decodeColor( colorString ); } //outline color QColor oc = mOutlineColor; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_COLOR ) ) { context.setOriginalValueVariable( QgsSymbolLayerV2Utils::encodeColor( mOutlineColor ) ); QString colorString = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_COLOR, context, QVariant(), &ok ).toString(); if ( ok ) oc = QgsSymbolLayerV2Utils::decodeColor( colorString ); } //symbol name QString symbolName = mSymbolName; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_SYMBOL_NAME ) ) { context.setOriginalValueVariable( mSymbolName ); symbolName = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_SYMBOL_NAME, context, mSymbolName ).toString(); } //offset double offsetX = 0; double offsetY = 0; markerOffset( context, offsetX, offsetY ); QPointF off( offsetX, offsetY ); //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle) double rotation = 0.0; if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_ROTATION ) ) { context.setOriginalValueVariable( mAngle ); rotation = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_ROTATION, context, mAngle ).toDouble() + mLineAngle; } else if ( !qgsDoubleNear( mAngle + mLineAngle, 0.0 ) ) { rotation = mAngle + mLineAngle; } rotation = -rotation; //rotation in Qt is counterclockwise if ( rotation ) off = _rotatedOffset( off, rotation ); QTransform t; t.translate( shift.x() + offsetX, shift.y() + offsetY ); if ( !qgsDoubleNear( rotation, 0.0 ) ) t.rotate( rotation ); double halfWidth = symbolWidth / 2.0; double halfHeight = symbolHeight / 2.0; if ( symbolName == "circle" ) { if ( qgsDoubleNear( halfWidth, halfHeight ) ) { QgsPointV2 pt( t.map( QPointF( 0, 0 ) ) ); e.writeFilledCircle( layerName, oc, pt, halfWidth ); } else { QgsPointSequenceV2 line; double stepsize = 2 * M_PI / 40; for ( int i = 0; i < 39; ++i ) { double angle = stepsize * i; double x = halfWidth * cos( angle ); double y = halfHeight * sin( angle ); line << QgsPointV2( t.map( QPointF( x, y ) ) ); } //close ellipse with first point line << line.at( 0 ); if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( QgsRingSequenceV2() << line, layerName, "SOLID", fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( line, layerName, "CONTINUOUS", oc, outlineWidth ); } } else if ( symbolName == "rectangle" ) { QgsPointSequenceV2 p; p << QgsPointV2( t.map( QPointF( -halfWidth, -halfHeight ) ) ) << QgsPointV2( t.map( QPointF( halfWidth, -halfHeight ) ) ) << QgsPointV2( t.map( QPointF( halfWidth, halfHeight ) ) ) << QgsPointV2( t.map( QPointF( -halfWidth, halfHeight ) ) ); p << p[0]; if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( QgsRingSequenceV2() << p, layerName, "SOLID", fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( p, layerName, "CONTINUOUS", oc, outlineWidth ); return true; } else if ( symbolName == "cross" && mPen.style() != Qt::NoPen ) { e.writePolyline( QgsPointSequenceV2() << QgsPointV2( t.map( QPointF( -halfWidth, 0 ) ) ) << QgsPointV2( t.map( QPointF( halfWidth, 0 ) ) ), layerName, "CONTINUOUS", oc, outlineWidth ); e.writePolyline( QgsPointSequenceV2() << QgsPointV2( t.map( QPointF( 0, halfHeight ) ) ) << QgsPointV2( t.map( QPointF( 0, -halfHeight ) ) ), layerName, "CONTINUOUS", oc, outlineWidth ); return true; } else if ( symbolName == "triangle" ) { QgsPointSequenceV2 p; p << QgsPointV2( t.map( QPointF( -halfWidth, -halfHeight ) ) ) << QgsPointV2( t.map( QPointF( halfWidth, -halfHeight ) ) ) << QgsPointV2( t.map( QPointF( 0, halfHeight ) ) ); p << p[0]; if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( QgsRingSequenceV2() << p, layerName, "SOLID", fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( p, layerName, "CONTINUOUS", oc, outlineWidth ); return true; } return false; //soon... }
void CWorld::Create(int width, int height, int textureID, float heightMap, int MPU, bool indoor, const string& bitmap) { m_width = width; m_height = height; m_MPU = MPU; m_inDoor = indoor; m_cameraPos = D3DXVECTOR3(MPU * -14, heightMap + MPU * 25, MPU * -14); m_cameraAngle.x = 45.0f; m_cameraAngle.y = -30.0f; _initialize(); int x, i, y, x2, y2; CLandscape* land; for (y = 0; y < m_height; y++) { for (x = 0; x < m_width; x++) { land = m_lands[y * m_width + x] = new CLandscape(m_device, this, x * MAP_SIZE, y * MAP_SIZE); land->GetLayer(textureID); } } QImage image; if (!bitmap.isEmpty() && image.load(bitmap)) { QTransform rot; rot.rotate(90); image = image.transformed(rot); for (y = 0; y < m_height; y++) { for (x = 0; x < m_width; x++) { land = m_lands[y * m_width + x]; for (x2 = 0; x2 < (MAP_SIZE + 1); x2++) { for (y2 = 0; y2 < (MAP_SIZE + 1); y2++) { land->m_heightMap[x2 *(MAP_SIZE + 1) + y2] = QColor(image.pixel( (int)(((float)(x2 + y * MAP_SIZE) / (float)(m_height * MAP_SIZE)) * (float)image.width()), (int)(((float)(y2 + x * MAP_SIZE) / (float)(m_width * MAP_SIZE)) * (float)image.height()) )).redF() * heightMap; } } } } } else { for (y = 0; y < m_height; y++) { for (x = 0; x < m_width; x++) { land = m_lands[y * m_width + x]; for (i = 0; i < (MAP_SIZE + 1) * (MAP_SIZE + 1); i++) land->m_heightMap[i] = heightMap; } } } }
void PageItem_Line::getVisualBoundingRect(double * x1, double * y1, double * x2, double * y2) const { double minx = std::numeric_limits<double>::max(); double miny = std::numeric_limits<double>::max(); double maxx = -std::numeric_limits<double>::max(); double maxy = -std::numeric_limits<double>::max(); double extraSpace = 0.0; if (NamedLStyle.isEmpty()) { if ((lineColor() != CommonStrings::None) || (!patternStrokeVal.isEmpty()) || (GrTypeStroke > 0)) { extraSpace = m_lineWidth / 2.0; if ((extraSpace == 0) && m_Doc->view()) // Hairline case extraSpace = 0.5 / m_Doc->view()->scale(); } if ((!patternStrokeVal.isEmpty()) && (m_Doc->docPatterns.contains(patternStrokeVal)) && (patternStrokePath)) { ScPattern *pat = &m_Doc->docPatterns[patternStrokeVal]; QTransform mat; mat.rotate(patternStrokeRotation); mat.scale(patternStrokeScaleX / 100.0, patternStrokeScaleY / 100.0); QRectF p1R = QRectF(0, 0, pat->width / 2.0, pat->height / 2.0); QRectF p2R = mat.map(p1R).boundingRect(); extraSpace = p2R.height(); } } else { multiLine ml = m_Doc->MLineStyles[NamedLStyle]; const SingleLine& sl = ml.last(); if (sl.Color != CommonStrings::None) { extraSpace = sl.Width / 2.0; if ((extraSpace == 0) && m_Doc->view()) // Hairline case extraSpace = 0.5 / m_Doc->view()->scale(); } } if (m_rotation != 0) { FPointArray pb; pb.resize(0); pb.addPoint(FPoint(0.0, -extraSpace, xPos(), yPos(), m_rotation, 1.0, 1.0)); pb.addPoint(FPoint(visualWidth(), -extraSpace, xPos(), yPos(), m_rotation, 1.0, 1.0)); pb.addPoint(FPoint(visualWidth(), +extraSpace, xPos(), yPos(), m_rotation, 1.0, 1.0)); pb.addPoint(FPoint(0.0, +extraSpace, xPos(), yPos(), m_rotation, 1.0, 1.0)); for (uint pc = 0; pc < 4; ++pc) { minx = qMin(minx, pb.point(pc).x()); miny = qMin(miny, pb.point(pc).y()); maxx = qMax(maxx, pb.point(pc).x()); maxy = qMax(maxy, pb.point(pc).y()); } *x1 = minx; *y1 = miny; *x2 = maxx; *y2 = maxy; } else { *x1 = m_xPos; *y1 = m_yPos - extraSpace; *x2 = m_xPos + visualWidth(); *y2 = m_yPos + extraSpace; } QRectF totalRect(QPointF(*x1, *y1), QPointF(*x2, *y2)); if (m_startArrowIndex != 0) { QTransform arrowTrans; FPointArray arrow = m_Doc->arrowStyles().at(m_startArrowIndex-1).points.copy(); arrowTrans.translate(m_xPos, m_yPos); arrowTrans.rotate(m_rotation); arrowTrans.translate(0, 0); arrowTrans.scale(m_startArrowScale / 100.0, m_startArrowScale / 100.0); if (NamedLStyle.isEmpty()) { if (m_lineWidth != 0.0) arrowTrans.scale(m_lineWidth, m_lineWidth); } else { multiLine ml = m_Doc->MLineStyles[NamedLStyle]; if (ml[ml.size()-1].Width != 0.0) arrowTrans.scale(ml[ml.size()-1].Width, ml[ml.size()-1].Width); } arrowTrans.scale(-1,1); arrow.map(arrowTrans); FPoint minAr = getMinClipF(&arrow); FPoint maxAr = getMaxClipF(&arrow); totalRect = totalRect.united(QRectF(QPointF(minAr.x(), minAr.y()), QPointF(maxAr.x(), maxAr.y()))); } if (m_endArrowIndex != 0) { QTransform arrowTrans; FPointArray arrow = m_Doc->arrowStyles().at(m_endArrowIndex-1).points.copy(); arrowTrans.translate(m_xPos, m_yPos); arrowTrans.rotate(m_rotation); arrowTrans.translate(m_width, 0); arrowTrans.scale(m_endArrowScale / 100.0, m_endArrowScale / 100.0); if (NamedLStyle.isEmpty()) { if (m_lineWidth != 0.0) arrowTrans.scale(m_lineWidth, m_lineWidth); } else { multiLine ml = m_Doc->MLineStyles[NamedLStyle]; if (ml[ml.size()-1].Width != 0.0) arrowTrans.scale(ml[ml.size()-1].Width, ml[ml.size()-1].Width); } arrow.map(arrowTrans); FPoint minAr = getMinClipF(&arrow); FPoint maxAr = getMaxClipF(&arrow); totalRect = totalRect.united(QRectF(QPointF(minAr.x(), minAr.y()), QPointF(maxAr.x(), maxAr.y()))); } totalRect.getCoords(x1, y1, x2, y2); }
void AbstractDiagram::Private::addLabel( LabelPaintCache* cache, const QModelIndex& index, const CartesianDiagramDataCompressor::CachePosition* position, const PositionPoints& points, const Position& autoPositionPositive, const Position& autoPositionNegative, const qreal value, qreal favoriteAngle /* = 0.0 */ ) { CartesianDiagramDataCompressor::AggregatedDataValueAttributes allAttrs( aggregatedAttrs( index, position ) ); QMap<QModelIndex, DataValueAttributes>::const_iterator it; for ( it = allAttrs.constBegin(); it != allAttrs.constEnd(); ++it ) { DataValueAttributes dva = it.value(); if ( !dva.isVisible() ) { continue; } const bool isPositive = ( value >= 0.0 ); RelativePosition relPos( dva.position( isPositive ) ); relPos.setReferencePoints( points ); if ( relPos.referencePosition().isUnknown() ) { relPos.setReferencePosition( isPositive ? autoPositionPositive : autoPositionNegative ); } // Rotate the label position (not the label itself) if the diagram is rotated so that the defaults still work if ( isTransposed() ) { KChartEnums::PositionValue posValue = relPos.referencePosition().value(); if ( posValue >= KChartEnums::PositionNorthWest && posValue <= KChartEnums::PositionWest ) { // rotate 90 degrees clockwise posValue = static_cast< KChartEnums::PositionValue >( posValue + 2 ); if ( posValue > KChartEnums::PositionWest ) { // wraparound posValue = static_cast< KChartEnums::PositionValue >( posValue - ( KChartEnums::PositionWest - KChartEnums::PositionNorthWest ) ); } relPos.setReferencePosition( Position( posValue ) ); } } const QPointF referencePoint = relPos.referencePoint(); if ( !diagram->coordinatePlane()->isVisiblePoint( referencePoint ) ) { continue; } const qreal fontHeight = cachedFontMetrics( dva.textAttributes(). calculatedFont( plane, KChartEnums::MeasureOrientationMinimum ), diagram )->height(); // Note: When printing data value texts and padding's Measure is using automatic reference area // detection, the font height is used as reference size for both horizontal and vertical // padding. QSizeF relativeMeasureSize( fontHeight, fontHeight ); if ( !dva.textAttributes().hasRotation() ) { TextAttributes ta = dva.textAttributes(); ta.setRotation( favoriteAngle ); dva.setTextAttributes( ta ); } // get the size of the label text using a subset of the information going into the final layout const QString text = formatDataValueText( dva, index, value ); QTextDocument doc; doc.setDocumentMargin( 0 ); if ( Qt::mightBeRichText( text ) ) { doc.setHtml( text ); } else { doc.setPlainText( text ); } const QFont calculatedFont( dva.textAttributes() .calculatedFont( plane, KChartEnums::MeasureOrientationMinimum ) ); doc.setDefaultFont( calculatedFont ); const QRectF plainRect = doc.documentLayout()->frameBoundingRect( doc.rootFrame() ); /** * A few hints on how the positioning of the text frame is done: * * Let's assume we have a bar chart, a text for a positive value * to be drawn, and "North" as attrs.positivePosition(). * * The reference point (pos) is then set to the top center point * of a bar. The offset now depends on the alignment: * * Top: text is centered horizontally to the bar, bottom of * text frame starts at top of bar * * Bottom: text is centered horizontally to the bar, top of * text frame starts at top of bar * * Center: text is centered horizontally to the bar, center * line of text frame is same as top of bar * * TopLeft: right edge of text frame is horizontal center of * bar, bottom of text frame is top of bar. * * ... * * Positive and negative value labels are treated equally, "North" * also refers to the top of a negative bar, and *not* to the bottom. * * * "NorthEast" likewise refers to the top right edge of the bar, * "NorthWest" to the top left edge of the bar, and so on. * * In other words, attrs.positivePosition() always refers to a * position of the *bar*, and relPos.alignment() always refers * to an alignment of the text frame relative to this position. */ QTransform transform; { // move to the general area where the label should be QPointF calcPoint = relPos.calculatedPoint( relativeMeasureSize ); transform.translate( calcPoint.x(), calcPoint.y() ); // align the text rect; find out by how many half-widths / half-heights to move. int dx = -1; if ( relPos.alignment() & Qt::AlignLeft ) { dx -= 1; } else if ( relPos.alignment() & Qt::AlignRight ) { dx += 1; } int dy = -1; if ( relPos.alignment() & Qt::AlignTop ) { dy -= 1; } else if ( relPos.alignment() & Qt::AlignBottom ) { dy += 1; } transform.translate( qreal( dx ) * plainRect.width() * 0.5, qreal( dy ) * plainRect.height() * 0.5 ); // rotate the text rect around its center transform.translate( plainRect.center().x(), plainRect.center().y() ); int rotation = dva.textAttributes().rotation(); if ( !isPositive && dva.mirrorNegativeValueTextRotation() ) { rotation *= -1; } transform.rotate( rotation ); transform.translate( -plainRect.center().x(), -plainRect.center().y() ); } QPainterPath labelArea; //labelArea.addPolygon( transform.mapToPolygon( plainRect.toRect() ) ); //labelArea.closeSubpath(); // Not doing that because QTransform has a special case for 180° that gives a different than // usual ordering of the points in the polygon returned by mapToPolygon( const QRect & ). // We expect a particular ordering in paintDataValueTextsAndMarkers() by using elementAt( 0 ), // and similar things might happen elsewhere. labelArea.addPolygon( transform.map( QPolygon( plainRect.toRect(), true ) ) ); // store the label geometry and auxiliary data cache->paintReplay.append( LabelPaintInfo( it.key(), dva, labelArea, referencePoint, value >= 0.0, text ) ); } }
void KWidget::setzRotateAngle( qreal angle ) { QTransform t = transform(); setTransform(t.rotate(angle, Qt::ZAxis)); }
void XfigPlug::processArrows(int forward_arrow, QString fArrowData, int backward_arrow, QString bArrowData, int depth, PageItem *ite) { int arrow_typeAF; // (enumeration type) int arrow_styleAF; // (enumeration type) float arrow_thicknessAF; // (1/80 inch) float arrow_widthAF; // (Fig units) float arrow_heightAF; // (Fig units) int arrow_typeAB; // (enumeration type) int arrow_styleAB; // (enumeration type) float arrow_thicknessAB; // (1/80 inch) float arrow_widthAB; // (Fig units) float arrow_heightAB; // (Fig units) FPointArray arrow; int z = -1; PageItem::ItemType iteType; if (forward_arrow == 1) { arrow.resize(0); ScTextStream CodeAF(&fArrowData, QIODevice::ReadOnly); CodeAF >> arrow_typeAF >> arrow_styleAF >> arrow_thicknessAF >> arrow_widthAF >> arrow_heightAF; arrow_widthAF = fig2Pts(arrow_widthAF); arrow_heightAF = fig2Pts(arrow_heightAF); arrow_thicknessAF = arrow_thicknessAF / 80.0 * 72.0; FPoint End = ite->PoLine.point(ite->PoLine.size()-2); for (uint xx = ite->PoLine.size()-1; xx > 0; xx -= 2) { FPoint Vector = ite->PoLine.point(xx); if ((End.x() != Vector.x()) || (End.y() != Vector.y())) { double r = atan2(End.y()-Vector.y(),End.x()-Vector.x())*(180.0/M_PI); QTransform arrowTrans; if (arrow_typeAF == 0) arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5"); else if (arrow_typeAF == 1) arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 z"); else if (arrow_typeAF == 2) arrow.parseSVG("M -1, -0.5 L 0, 0 L -1, 0.5 L -0.7 0 z"); else if (arrow_typeAF == 3) arrow.parseSVG("M -0.7, -0.5 L 0, 0 L -0.7, 0.5 L -1 0 z"); arrowTrans.translate(End.x(), End.y()); arrowTrans.rotate(r); arrowTrans.scale(arrow_heightAF, arrow_widthAF); arrow.map(arrowTrans); break; } } QString fillC = "White"; if (arrow_styleAF == 1) fillC = CurrColorStroke; if (arrow_typeAF == 0) { fillC = CommonStrings::None; iteType = PageItem::PolyLine; } else iteType = PageItem::Polygon; z = m_Doc->itemAdd(iteType, PageItem::Unspecified, ite->xPos(), ite->yPos(), 10, 10, arrow_thicknessAF, fillC, CurrColorStroke, true); if (z >= 0) { PageItem *item = m_Doc->Items->at(z); item->PoLine = arrow.copy(); item->ClipEdited = true; item->FrameType = 3; item->setFillShade(CurrFillShade); item->setLineShade(CurrStrokeShade); FPoint wh = getMaxClipF(&item->PoLine); item->setWidthHeight(wh.x(),wh.y()); item->setTextFlowMode(PageItem::TextFlowDisabled); m_Doc->AdjustItemSize(item); item->setWidthHeight(qMax(item->width(), 1.0), qMax(item->height(), 1.0)); depthMap.insert(999 - depth, currentItemNr); currentItemNr++; } }
void KMultiTabBarTab::paintEvent(QPaintEvent*) { QPainter painter(this); QStyleOptionToolButton opt; initStyleOption(&opt); // Paint bevel.. if (underMouse() || isChecked()) { opt.text.clear(); opt.icon = QIcon(); style()->drawComplexControl(QStyle::CC_ToolButton, &opt, &painter, this); } int hMargin, vMargin; computeMargins(&hMargin, &vMargin); // We first figure out how much room we have for the text, based on // icon size and margin, try to fit in by eliding, and perhaps // give up on drawing the text entirely if we're too short on room QPixmap icon = iconPixmap(); int textRoom = 0; int iconRoom = 0; QString t; if (shouldDrawText()) { if (isVertical()) { iconRoom = icon.height() + 2*vMargin; textRoom = height() - iconRoom - vMargin; } else { iconRoom = icon.width() + 2*hMargin; textRoom = width() - iconRoom - hMargin; } t = painter.fontMetrics().elidedText(text(), Qt::ElideRight, textRoom); // See whether anything is left. Qt will return either // ... or the ellipsis unicode character, 0x2026 if (t == QLatin1String("...") || t == QChar(0x2026)) t.clear(); } // Label time.... Simple case: no text, so just plop down the icon right in the center // We only do this when the button never draws the text, to avoid jumps in icon position // when resizing if (!shouldDrawText()) { style()->drawItemPixmap(&painter, rect(), Qt::AlignCenter | Qt::AlignVCenter, icon); return; } // Now where the icon/text goes depends on text direction and tab position QRect iconArea; QRect labelArea; bool bottomIcon = false; bool rtl = layoutDirection() == Qt::RightToLeft; if (isVertical()) { if (m_position == KMultiTabBar::Left && !rtl) bottomIcon = true; if (m_position == KMultiTabBar::Right && rtl) bottomIcon = true; } //alignFlags = Qt::AlignLeading | Qt::AlignVCenter; if (isVertical()) { if (bottomIcon) { labelArea = QRect(0, vMargin, width(), textRoom); iconArea = QRect(0, vMargin + textRoom, width(), iconRoom); } else { labelArea = QRect(0, iconRoom, width(), textRoom); iconArea = QRect(0, 0, width(), iconRoom); } } else { // Pretty simple --- depends only on RTL/LTR if (rtl) { labelArea = QRect(hMargin, 0, textRoom, height()); iconArea = QRect(hMargin + textRoom, 0, iconRoom, height()); } else { labelArea = QRect(iconRoom, 0, textRoom, height()); iconArea = QRect(0, 0, iconRoom, height()); } } style()->drawItemPixmap(&painter, iconArea, Qt::AlignCenter | Qt::AlignVCenter, icon); if (t.isEmpty()) return; QRect labelPaintArea = labelArea; if (isVertical()) { // If we're vertical, we paint to a simple 0,0 origin rect, // and get the transformations to get us in the right place labelPaintArea = QRect(0, 0, labelArea.height(), labelArea.width()); QTransform tr; if (bottomIcon) { tr.translate(labelArea.x(), labelPaintArea.width() + labelArea.y()); tr.rotate(-90); } else { tr.translate(labelPaintArea.height() + labelArea.x(), labelArea.y()); tr.rotate(90); } painter.setTransform(tr); } style()->drawItemText(&painter, labelPaintArea, Qt::AlignLeading | Qt::AlignVCenter, palette(), true, t, QPalette::ButtonText); }
// -------------------------------------------------------- void TouchWidgetRenderer::drawResizers( GLResourceContainer * container, const SceneTouchPoint * resizing_point, const QPointF & circle_center, float circle_radius, const QPointF & base_target, QList<float> resizer_angles ) const { static Warping<qreal> resizer_activeness(0.0f, 0.2f); static bool resizer_active = false; static QPointF last_resizer_pos; static float touch_angle_target = 0; QPointF base_pos = QLineF(circle_center, base_target).unitVector().pointAt(circle_radius); float base_angle = QLineF(base_target, circle_center).angleTo(QLineF(0,0,1,0)); // trigger the warp towards 1 or 0 if the status just changed and evaluate it if((resizing_point != NULL) != resizer_active) { resizer_active = (resizing_point != NULL); resizer_activeness.setTarget(resizer_active ? 1.0f : 0.0f); } float activeness = resizer_activeness.value(); // update resizer position and angle based on current touch if(resizer_active) { last_resizer_pos = resizing_point->pos(); touch_angle_target = QLineF(last_resizer_pos, circle_center).angleTo(QLineF(0,0,1,0));; touch_angle_target += 60; while(touch_angle_target>120) touch_angle_target-=120; while(touch_angle_target<-120) touch_angle_target+=120; touch_angle_target -= 60; } // compute resizer size const float resizer_diameter = 0.3f * circle_radius * (activeness*0.5+1); QSizeF resizer_size(resizer_diameter, resizer_diameter); // draw individual angles foreach(float resizer_angle, resizer_angles) { // compute desired angle float blended_angle = (touch_angle_target+resizer_angle)*activeness + resizer_angle*(1-activeness); // compute resizer handle location QTransform transform; transform.translate(circle_center.x(), circle_center.y()); transform.rotate(blended_angle); transform.translate(-circle_center.x(), -circle_center.y()); QPointF resizer_pos = transform.map(base_pos); // draw resizer handle if(activeness < 1) { drawTexturedQuad(container->texture("mglass_resizer"), resizer_pos, resizer_size, blended_angle+base_angle+180); } if(activeness > 0) { drawTexturedQuad(container->texture("mglass_resizer_active"), resizer_pos, resizer_size, blended_angle+base_angle+180, activeness); } }
void PageItem_Spiral::DrawObj_Item(ScPainter *p, QRectF /*e*/) { if (m_Doc->RePos || PoLine.size() < 4) return; if (!m_Doc->layerOutline(m_layerID)) { if ((fillColor() != CommonStrings::None) || (GrType != 0)) { FPointArray cli; FPoint Start; bool firstp = true; for (int n = 0; n < PoLine.size()-3; n += 4) { if (firstp) { Start = PoLine.point(n); firstp = false; } if (PoLine.isMarker(n)) { cli.addPoint(PoLine.point(n-2)); cli.addPoint(PoLine.point(n-2)); cli.addPoint(Start); cli.addPoint(Start); cli.setMarker(); firstp = true; continue; } cli.addPoint(PoLine.point(n)); cli.addPoint(PoLine.point(n+1)); cli.addPoint(PoLine.point(n+2)); cli.addPoint(PoLine.point(n+3)); } if (cli.size() > 2) { FPoint l1 = cli.point(cli.size()-2); cli.addPoint(l1); cli.addPoint(l1); cli.addPoint(Start); cli.addPoint(Start); } p->setupPolygon(&cli); p->fillPath(); } p->setupPolygon(&PoLine, false); if (NamedLStyle.isEmpty()) { if ((!patternStrokeVal.isEmpty()) && (m_Doc->docPatterns.contains(patternStrokeVal))) { if (patternStrokePath) { QPainterPath guidePath = PoLine.toQPainterPath(false); DrawStrokePattern(p, guidePath); } else { p->setPattern(&m_Doc->docPatterns[patternStrokeVal], patternStrokeScaleX, patternStrokeScaleY, patternStrokeOffsetX, patternStrokeOffsetY, patternStrokeRotation, patternStrokeSkewX, patternStrokeSkewY, patternStrokeMirrorX, patternStrokeMirrorY); p->setStrokeMode(ScPainter::Pattern); p->strokePath(); } } else if (GrTypeStroke > 0) { if ((!gradientStrokeVal.isEmpty()) && (!m_Doc->docGradients.contains(gradientStrokeVal))) gradientStrokeVal = ""; if (!(gradientStrokeVal.isEmpty()) && (m_Doc->docGradients.contains(gradientStrokeVal))) stroke_gradient = m_Doc->docGradients[gradientStrokeVal]; if (stroke_gradient.stops() < 2) // fall back to solid stroking if there are not enough colorstops in the gradient. { if (lineColor() != CommonStrings::None) { p->setBrush(strokeQColor); p->setStrokeMode(ScPainter::Solid); } else { no_stroke = true; p->setStrokeMode(ScPainter::None); } } else { p->setStrokeMode(ScPainter::Gradient); p->stroke_gradient = stroke_gradient; if (GrTypeStroke == 6) p->setGradient(VGradient::linear, FPoint(GrStrokeStartX, GrStrokeStartY), FPoint(GrStrokeEndX, GrStrokeEndY), FPoint(GrStrokeStartX, GrStrokeStartY), GrStrokeScale, GrStrokeSkew); else p->setGradient(VGradient::radial, FPoint(GrStrokeStartX, GrStrokeStartY), FPoint(GrStrokeEndX, GrStrokeEndY), FPoint(GrStrokeFocalX, GrStrokeFocalY), GrStrokeScale, GrStrokeSkew); } p->strokePath(); } else if (lineColor() != CommonStrings::None) { p->setStrokeMode(ScPainter::Solid); p->strokePath(); } else no_stroke = true; } else { p->setStrokeMode(ScPainter::Solid); multiLine ml = m_Doc->MLineStyles[NamedLStyle]; QColor tmp; for (int it = ml.size()-1; it > -1; it--) { if (ml[it].Color != CommonStrings::None) // && (ml[it].Width != 0)) { SetQColor(&tmp, ml[it].Color, ml[it].Shade); p->setPen(tmp, ml[it].Width, static_cast<Qt::PenStyle>(ml[it].Dash), static_cast<Qt::PenCapStyle>(ml[it].LineEnd), static_cast<Qt::PenJoinStyle>(ml[it].LineJoin)); p->strokePath(); } } } } if (m_startArrowIndex != 0) { FPoint Start = PoLine.point(0); for (int xx = 1; xx < PoLine.size(); xx += 2) { FPoint Vector = PoLine.point(xx); if ((Start.x() != Vector.x()) || (Start.y() != Vector.y())) { double r = atan2(Start.y()-Vector.y(),Start.x()-Vector.x())*(180.0/M_PI); QTransform arrowTrans; arrowTrans.translate(Start.x(), Start.y()); arrowTrans.rotate(r); arrowTrans.scale(m_startArrowScale / 100.0, m_startArrowScale / 100.0); drawArrow(p, arrowTrans, m_startArrowIndex); break; } } } if (m_endArrowIndex != 0) { FPoint End = PoLine.point(PoLine.size()-2); for (uint xx = PoLine.size()-1; xx > 0; xx -= 2) { FPoint Vector = PoLine.point(xx); if ((End.x() != Vector.x()) || (End.y() != Vector.y())) { double r = atan2(End.y()-Vector.y(),End.x()-Vector.x())*(180.0/M_PI); QTransform arrowTrans; arrowTrans.translate(End.x(), End.y()); arrowTrans.rotate(r); arrowTrans.scale(m_endArrowScale / 100.0, m_endArrowScale / 100.0); drawArrow(p, arrowTrans, m_endArrowIndex); break; } } } }
void World::paintWorld(QPainter *painter) { if (!_isGameOver) { for (int q = 0; q < _tankList.size(); q++) { QTransform transform; int angle = 0; switch (_tankList[q]->getAngle()) { case 1: { angle = 90; break; } case 2: { angle = 180; break; } case 3: { angle = 270; break; } } transform.rotate(angle); QImage image; if (_tankList[q]->getKillAnimation() == 0) { if (_tankList[q]->getTeam() == 1) { image = *_images[0]; } else if (_tankList[q]->getTeam() == 0) { image = *_images[1]; } else if (_tankList[q]->getTeam() == 2) { image = *_images[9]; painter->drawImage(_tankList[q]->getPos(),image); continue; } image = image.transformed(transform); painter->drawImage(_tankList[q]->getPos(),image); } else { image = *_images[7]; painter->drawImage(_tankList[q]->getPos().x() + _tankList[q]->getSize() / 2 - image.width() / 4, _tankList[q]->getPos().y() + _tankList[q]->getSize() / 2 - image.height() / 4 , image); } } for (int q = 0; q < _wallList.size(); q++) { QImage image; switch (_wallList[q]->getType()) { case 0: { image = *_images[2]; break; } case 1: { image = *_images[3]; break; } case 2: { image = *_images[5]; break; } } painter->drawImage(_wallList[q]->getPos(), image); } for (int q = 0; q < _bulletList.size(); q++) { QTransform transform; int angle = 0; switch (_bulletList[q]->getAngle()) { case 1: { angle = 90; break; } case 2: { angle = 180; break; } case 3: { angle = 270; break; } } transform.rotate(angle); QImage image; if (_bulletList[q]->getKillAnimation() == 0) { image = _images[4]->transformed(transform); painter->drawImage(_bulletList[q]->getPos(),image); } else { image = *_images[6]; painter->drawImage(_bulletList[q]->getPos().x() + _bulletList[q]->getSize() / 2 - image.width() / 2, _bulletList[q]->getPos().y() + _bulletList[q]->getSize() / 2 - image.height() / 2 ,image); } } } else { painter->drawImage(140,205, *_images[8]); } }
void PageItem_Line::getBoundingRect(double *x1, double *y1, double *x2, double *y2) const { double minx = std::numeric_limits<double>::max(); double miny = std::numeric_limits<double>::max(); double maxx = -std::numeric_limits<double>::max(); double maxy = -std::numeric_limits<double>::max(); if (m_rotation != 0) { FPointArray pb; pb.resize(0); pb.addPoint(FPoint(0, -m_lineWidth / 2.0, m_xPos, m_yPos, m_rotation, 1.0, 1.0)); pb.addPoint(FPoint(m_width, -m_lineWidth / 2.0, m_xPos, m_yPos, m_rotation, 1.0, 1.0)); pb.addPoint(FPoint(m_width, +m_lineWidth / 2.0, m_xPos, m_yPos, m_rotation, 1.0, 1.0)); pb.addPoint(FPoint(0, +m_lineWidth / 2.0, m_xPos, m_yPos, m_rotation, 1.0, 1.0)); for (uint pc = 0; pc < 4; ++pc) { minx = qMin(minx, pb.point(pc).x()); miny = qMin(miny, pb.point(pc).y()); maxx = qMax(maxx, pb.point(pc).x()); maxy = qMax(maxy, pb.point(pc).y()); } *x1 = minx; *y1 = miny; *x2 = maxx; *y2 = maxy; } else { *x1 = m_xPos; *y1 = m_yPos - qMax(1.0, m_lineWidth) / 2.0; *x2 = m_xPos + m_width; *y2 = m_yPos + qMax(1.0, m_lineWidth) / 2.0; } QRectF totalRect = QRectF(QPointF(*x1, *y1), QPointF(*x2, *y2)); if (m_startArrowIndex != 0) { QTransform arrowTrans; FPointArray arrow = m_Doc->arrowStyles().at(m_startArrowIndex-1).points.copy(); arrowTrans.translate(m_xPos, m_yPos); arrowTrans.rotate(m_rotation); arrowTrans.translate(0, 0); arrowTrans.scale(m_startArrowScale / 100.0, m_startArrowScale / 100.0); if (NamedLStyle.isEmpty()) { if (m_lineWidth != 0.0) arrowTrans.scale(m_lineWidth, m_lineWidth); } else { multiLine ml = m_Doc->MLineStyles[NamedLStyle]; if (ml[ml.size()-1].Width != 0.0) arrowTrans.scale(ml[ml.size()-1].Width, ml[ml.size()-1].Width); } arrowTrans.scale(-1,1); arrow.map(arrowTrans); FPoint minAr = getMinClipF(&arrow); FPoint maxAr = getMaxClipF(&arrow); totalRect = totalRect.united(QRectF(QPointF(minAr.x(), minAr.y()), QPointF(maxAr.x(), maxAr.y()))); } if (m_endArrowIndex != 0) { QTransform arrowTrans; FPointArray arrow = m_Doc->arrowStyles().at(m_endArrowIndex-1).points.copy(); arrowTrans.translate(m_xPos, m_yPos); arrowTrans.rotate(m_rotation); arrowTrans.translate(m_width, 0); arrowTrans.scale(m_endArrowScale / 100.0, m_endArrowScale / 100.0); if (NamedLStyle.isEmpty()) { if (m_lineWidth != 0.0) arrowTrans.scale(m_lineWidth, m_lineWidth); } else { multiLine ml = m_Doc->MLineStyles[NamedLStyle]; if (ml[ml.size()-1].Width != 0.0) arrowTrans.scale(ml[ml.size()-1].Width, ml[ml.size()-1].Width); } arrow.map(arrowTrans); FPoint minAr = getMinClipF(&arrow); FPoint maxAr = getMaxClipF(&arrow); totalRect = totalRect.united(QRectF(QPointF(minAr.x(), minAr.y()), QPointF(maxAr.x(), maxAr.y()))); } totalRect.getCoords(x1, y1, x2, y2); }
bool PathAlongPathPlugin::run(ScribusDoc* doc, const QString&) { firstUpdate = true; m_doc = doc; originalPathG.clear(); originalRotG.clear(); originalXPosG.clear(); originalYPosG.clear(); patternItemG.clear(); if (m_doc == nullptr) m_doc = ScCore->primaryMainWindow()->doc; if (m_doc->m_Selection->count() > 1) { if ((m_doc->m_Selection->itemAt(0)->isGroup()) || (m_doc->m_Selection->itemAt(1)->isGroup())) { selOffs = 0; selCount = m_doc->m_Selection->count() - 1; if (!m_doc->m_Selection->itemAt(0)->isGroup()) { pathItem = m_doc->m_Selection->itemAt(0); selOffs = 1; } else pathItem = m_doc->m_Selection->itemAt(selCount); effectPath = pathItem->PoLine.copy(); QTransform mp; mp.rotate(pathItem->rotation()); effectPath.map(mp); PageItem* bxi = m_doc->m_Selection->itemAt(selOffs); bxi->asGroupFrame()->adjustXYPosition(); originalPathG.append(bxi->PoLine.copy()); originalXPosG.append(bxi->xPos()); originalYPosG.append(bxi->yPos()); originalXPosGi.append(bxi->gXpos); originalYPosGi.append(bxi->gYpos); originalRotG.append(bxi->rotation()); originalWidth.append(bxi->width()); originalHeight.append(bxi->height()); originalWidthG.append(bxi->groupWidth); originalHeightG.append(bxi->groupHeight); patternItemG.append(bxi); QList<PageItem*> bxiL = bxi->getAllChildren(); for (int bx = 0; bx < bxiL.count(); ++bx) { PageItem* cIte = bxiL.at(bx); originalPathG.append(cIte->PoLine.copy()); originalXPosG.append(cIte->xPos()); originalYPosG.append(cIte->yPos()); originalWidth.append(cIte->width()); originalHeight.append(cIte->height()); originalWidthG.append(cIte->groupWidth); originalHeightG.append(cIte->groupHeight); originalXPosGi.append(cIte->gXpos); originalYPosGi.append(cIte->gYpos); originalRotG.append(cIte->rotation()); patternItemG.append(cIte); } QPainterPath tmpPath = effectPath.toQPainterPath(false); PathDialog *dia = new PathDialog(m_doc->scMW(), m_doc->unitIndex(), tmpPath.length(), true); connect(dia, SIGNAL(updateValues(int, double, double, double, int)), this, SLOT(updateEffectG(int, double, double, double, int))); if (dia->exec()) { updateEffectG(dia->effectType, dia->offset, dia->offsetY, dia->gap, dia->rotate); m_doc->changed(); if (bxi->isGroup()) { m_doc->resizeGroupToContents(bxi); bxi->SetRectFrame(); m_doc->view()->DrawNew(); } } else { updateEffectG(-1, dia->offset, dia->offsetY, dia->gap, dia->rotate); m_doc->view()->DrawNew(); } delete dia; } else {
QPainterPath QGIViewPart::drawPainterPath(TechDrawGeometry::BaseGeom *baseGeom) const { QPainterPath path; switch(baseGeom->geomType) { case TechDrawGeometry::CIRCLE: { TechDrawGeometry::Circle *geom = static_cast<TechDrawGeometry::Circle *>(baseGeom); double x = geom->center.fX - geom->radius; double y = geom->center.fY - geom->radius; path.addEllipse(x, y, geom->radius * 2, geom->radius * 2); //topleft@(x,y) radx,rady //Base::Console().Message("TRACE -drawPainterPath - making an CIRCLE @(%.3f,%.3f) R:%.3f\n",x, y, geom->radius); } break; case TechDrawGeometry::ARCOFCIRCLE: { TechDrawGeometry::AOC *geom = static_cast<TechDrawGeometry::AOC *>(baseGeom); //double x = geom->center.fX - geom->radius; //double y = geom->center.fY - geom->radius; pathArc(path, geom->radius, geom->radius, 0., geom->largeArc, geom->cw, geom->endPnt.fX, geom->endPnt.fY, geom->startPnt.fX, geom->startPnt.fY); //Base::Console().Message("TRACE -drawPainterPath - making an ARCOFCIRCLE @(%.3f,%.3f) R:%.3f\n",x, y, geom->radius); } break; case TechDrawGeometry::ELLIPSE: { TechDrawGeometry::Ellipse *geom = static_cast<TechDrawGeometry::Ellipse *>(baseGeom); // Calculate start and end points as ellipse with theta = 0 and pi double startX = geom->center.fX + geom->major * cos(geom->angle), startY = geom->center.fY + geom->major * sin(geom->angle), endX = geom->center.fX - geom->major * cos(geom->angle), endY = geom->center.fY - geom->major * sin(geom->angle); pathArc(path, geom->major, geom->minor, geom->angle, false, false, endX, endY, startX, startY); pathArc(path, geom->major, geom->minor, geom->angle, false, false, startX, startY, endX, endY); //Base::Console().Message("TRACE -drawPainterPath - making an ELLIPSE @(%.3f,%.3f) R1:%.3f R2:%.3f\n",x, y, geom->major, geom->minor); } break; case TechDrawGeometry::ARCOFELLIPSE: { TechDrawGeometry::AOE *geom = static_cast<TechDrawGeometry::AOE *>(baseGeom); pathArc(path, geom->major, geom->minor, geom->angle, geom->largeArc, geom->cw, geom->endPnt.fX, geom->endPnt.fY, geom->startPnt.fX, geom->startPnt.fY); //Base::Console().Message("TRACE -drawPainterPath - making an ARCOFELLIPSE R1:%.3f R2:%.3f From: (%.3f,%.3f) To: (%.3f,%.3f)\n",geom->major, geom->minor,geom->startPnt.fX, geom->startPnt.fY,geom->endPnt.fX, geom->endPnt.fY); } break; case TechDrawGeometry::BSPLINE: { TechDrawGeometry::BSpline *geom = static_cast<TechDrawGeometry::BSpline *>(baseGeom); std::vector<TechDrawGeometry::BezierSegment>::const_iterator it = geom->segments.begin(); // Move painter to the beginning of our first segment path.moveTo(it->pnts[0].fX, it->pnts[0].fY); //Base::Console().Message("TRACE -drawPainterPath - making an BSPLINE From: (%.3f,%.3f)\n",it->pnts[0].fX,it->pnts[0].fY); for ( ; it != geom->segments.end(); ++it) { // At this point, the painter is either at the beginning // of the first segment, or end of the last if ( it->poles == 2 ) { // Degree 1 bezier = straight line... path.lineTo(it->pnts[1].fX, it->pnts[1].fY); } else if ( it->poles == 3 ) { path.quadTo(it->pnts[1].fX, it->pnts[1].fY, it->pnts[2].fX, it->pnts[2].fY); } else if ( it->poles == 4 ) { path.cubicTo(it->pnts[1].fX, it->pnts[1].fY, it->pnts[2].fX, it->pnts[2].fY, it->pnts[3].fX, it->pnts[3].fY); } else { //can only handle lines,quads,cubes Base::Console().Error("Bad pole count (%d) for BezierSegment of BSpline geometry\n",it->poles); path.lineTo(it->pnts[1].fX, it->pnts[1].fY); //show something for debugging } } } break; case TechDrawGeometry::GENERIC: { TechDrawGeometry::Generic *geom = static_cast<TechDrawGeometry::Generic *>(baseGeom); path.moveTo(geom->points[0].fX, geom->points[0].fY); std::vector<Base::Vector2D>::const_iterator it = geom->points.begin(); //Base::Console().Message("TRACE -drawPainterPath - making an GENERIC From: (%.3f,%.3f)\n",geom->points[0].fX, geom->points[0].fY); for(++it; it != geom->points.end(); ++it) { path.lineTo((*it).fX, (*it).fY); //Base::Console().Message(">>>> To: (%.3f,%.3f)\n",(*it).fX, (*it).fY); } } break; default: Base::Console().Error("Error - drawPainterPath - UNKNOWN geomType: %d\n",baseGeom->geomType); break; } double rot = getViewObject()->Rotation.getValue(); if (rot) { QTransform t; t.rotate(-rot); path = t.map(path); } return path; }
void FancyTabProxyStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *p, const QWidget *widget) const { const QStyleOptionTabV3 *v3Opt = qstyleoption_cast<const QStyleOptionTabV3*>(option); if (element != CE_TabBarTab || !v3Opt) { QProxyStyle::drawControl(element, option, p, widget); return; } const QRect rect = v3Opt->rect; const bool selected = v3Opt->state &State_Selected; const bool verticalTabs = v3Opt->shape == QTabBar::RoundedWest; const QString text = v3Opt->text; QTransform m; if (verticalTabs) { m = QTransform::fromTranslate(rect.left(), rect.bottom()); m.rotate(-90); } else { m = QTransform::fromTranslate(rect.left(), rect.top()); } const QRect draw_rect(QPoint(0, 0), m.mapRect(rect).size()); if (!selected && GtkStyle::isActive()) { p->fillRect(option->rect, option->palette.background()); } p->save(); p->setTransform(m); QRect iconRect(QPoint(8, 0), v3Opt->iconSize); QRect textRect(iconRect.topRight() + QPoint(4, 0), draw_rect.size()); textRect.setRight(draw_rect.width()); iconRect.translate(0, (draw_rect.height() - iconRect.height()) / 2); QStyleOptionViewItemV4 styleOpt; styleOpt.palette=option->palette; styleOpt.rect=draw_rect; if (QStyleOptionTab::Beginning==v3Opt->position) { styleOpt.rect.adjust(0, 0, -1, 0); } styleOpt.state=option->state; styleOpt.state&=~(QStyle::State_Selected|QStyle::State_MouseOver); styleOpt.state|=QStyle::State_Selected|QStyle::State_Enabled; styleOpt.viewItemPosition = QStyleOptionViewItemV4::OnlyOne; styleOpt.showDecorationSelected=true; bool drawBgnd=true; int fader = 1; if (!selected && drawBgnd) { const QString faderKey = "tab_" + text + "_fader"; const QString animationKey = "tab_" + text + "_animation"; const QString tab_hover = widget->property("tab_hover").toString(); fader=widget->property(faderKey.toUtf8().constData()).toInt(); QPropertyAnimation *animation = widget->property(animationKey.toUtf8().constData()).value<QPropertyAnimation*>(); if (!animation) { QWidget* mut_widget = const_cast<QWidget*>(widget); fader = 0; mut_widget->setProperty(faderKey.toUtf8().constData(), fader); animation = new QPropertyAnimation(mut_widget, faderKey.toUtf8(), mut_widget); connect(animation, SIGNAL(valueChanged(QVariant)), mut_widget, SLOT(update())); mut_widget->setProperty(animationKey.toUtf8().constData(), QVariant::fromValue(animation)); } if (text == tab_hover) { if (animation->state() != QAbstractAnimation::Running && fader != 40) { animation->stop(); animation->setDuration(80); animation->setEndValue(50); animation->start(); } } else { if (animation->state() != QAbstractAnimation::Running && fader != 0) { animation->stop(); animation->setDuration(160); animation->setEndValue(0); animation->start(); } } if (fader<1) { drawBgnd=false; } else { QColor col(styleOpt.palette.highlight().color()); col.setAlpha(fader); styleOpt.palette.setColor(styleOpt.palette.currentColorGroup(), QPalette::Highlight, col); } } if (drawBgnd) { if (!selected && GtkStyle::isActive()) { GtkStyle::drawSelection(styleOpt, p, (fader*1.0)/150.0); } else { #ifdef Q_OS_MAC OSXStyle::self()->drawSelection(styleOpt, p, selected ? 1.0 : (fader*1.0)/150.0); #else #ifdef Q_OS_WIN if (QPalette::Active!=styleOpt.palette.currentColorGroup()) { styleOpt.palette.setColor(QPalette::Highlight, styleOpt.palette.color(QPalette::Window).darker(110)); } #endif QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &styleOpt, p, 0); #endif } } int textFlags = Qt::AlignTop | Qt::AlignVCenter; #ifdef Q_OS_MAC p->setPen(selected && option->state&State_Active ? OSXStyle::self()->viewPalette().highlightedText().color() : OSXStyle::self()->viewPalette().foreground().color()); #else p->setPen(selected && option->state&State_Active ? QApplication::palette().highlightedText().color() : QApplication::palette().foreground().color()); #endif drawIcon(v3Opt->icon, iconRect, p, v3Opt->iconSize, selected && option->state&State_Active); QString txt=text; txt.replace("&", ""); txt=p->fontMetrics().elidedText(txt, elideMode(), textRect.width()); p->drawText(textRect.translated(0, -1), textFlags, txt); p->restore(); }
QPainterPath ArtisticTextToolSelection::outline() { if (!hasSelection()) return QPainterPath(); CharIndex charPos = m_currentShape->indexOfChar(m_selectionStart); if (charPos.first < 0) return QPainterPath(); QPainterPath outline; QPolygonF polygon; QList<ArtisticTextRange> ranges = m_currentShape->text(); int globalCharIndex = m_selectionStart; int remainingChars = m_selectionCount; while (remainingChars) { const ArtisticTextRange ¤tRange = ranges[charPos.first]; int currentTextLength = currentRange.text().length(); while (charPos.second < currentTextLength && remainingChars > 0) { const QPointF pos = m_currentShape->charPositionAt(globalCharIndex); const qreal angle = m_currentShape->charAngleAt(globalCharIndex); QTransform charTransform; charTransform.translate( pos.x() - 1, pos.y() ); charTransform.rotate( 360. - angle ); QFontMetricsF metrics(currentRange.font()); polygon.prepend(charTransform.map(QPointF(0.0, -metrics.ascent()))); polygon.append(charTransform.map(QPointF(0.0, metrics.descent()))); // advance to next character charPos.second++; globalCharIndex++; remainingChars--; // next character has y-offset or we are at the end of this text range const bool hasYOffset = currentRange.hasYOffset(charPos.second); const bool atRangeEnd = charPos.second == currentTextLength; const bool atSelectionEnd = remainingChars == 0; if (hasYOffset || atRangeEnd || atSelectionEnd) { if (hasYOffset || atRangeEnd) { const QChar c = currentRange.text().at(charPos.second-1); const qreal w = metrics.width(c); polygon.prepend(charTransform.map(QPointF(w, -metrics.ascent()))); polygon.append(charTransform.map(QPointF(w, metrics.descent()))); } else { const QPointF pos = m_currentShape->charPositionAt(globalCharIndex); const qreal angle = m_currentShape->charAngleAt(globalCharIndex); charTransform.reset(); charTransform.translate( pos.x() - 1, pos.y() ); charTransform.rotate( 360. - angle ); polygon.prepend(charTransform.map(QPointF(0.0, -metrics.ascent()))); polygon.append(charTransform.map(QPointF(0.0, metrics.descent()))); } QPainterPath p; p.addPolygon(polygon); outline = outline.united(p); polygon.clear(); } } // go to first character of next text range charPos.first++; charPos.second = 0; } // transform to document coordinates return m_currentShape->absoluteTransformation(0).map(outline); }
bool DataConverter::digitalPattern_Rotate(QPolygonF &points, qreal angle) { if (angle == 0.0) return true; if (angle < -180.0 || angle > 180.0) { qDebug("[DataConverter::digitalPattern_Rotate] Error: Angle: [%f]", angle); return false; } if (points.size() < 10) { qDebug("[DataConverter::digitalPattern_Rotate] Error: Polygon Point Count: [%d]", points.size()); return false; } // QTransform transform; transform.rotate(angle); points = transform.map(points); // int bottomIndex = 0; { qreal tmpX = -9999.99; for (int i = 0; i < points.size(); i++) { if (points.at(i).y() < 0.0) continue; if (points.at(i).x() > 0.0) continue; if (points.at(i).x() > tmpX) { tmpX = points.at(i).x(); bottomIndex = i; } } } qDebug("** bottomIndex: [%d]", bottomIndex); if (bottomIndex > 0) { QPointF tmpPoint; for (int i = points.size() - 1; i >= bottomIndex; i--) { tmpPoint = points.last(); points.pop_back(); points.push_front(tmpPoint); } } return true; }
bool QgsEllipseSymbolLayer::writeDxf( QgsDxfExport &e, double mmMapUnitScaleFactor, const QString &layerName, QgsSymbolRenderContext &context, QPointF shift ) const { //width double symbolWidth = mSymbolWidth; if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyWidth ) ) //1. priority: data defined setting on symbol layer le { context.setOriginalValueVariable( mSymbolWidth ); symbolWidth = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::PropertyWidth, context.renderContext().expressionContext(), mSymbolWidth ); } if ( mSymbolWidthUnit == QgsUnitTypes::RenderMillimeters ) { symbolWidth *= mmMapUnitScaleFactor; } //height double symbolHeight = mSymbolHeight; if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyHeight ) ) //1. priority: data defined setting on symbol layer level { context.setOriginalValueVariable( mSymbolHeight ); symbolWidth = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::PropertyHeight, context.renderContext().expressionContext(), mSymbolHeight ); } if ( mSymbolHeightUnit == QgsUnitTypes::RenderMillimeters ) { symbolHeight *= mmMapUnitScaleFactor; } //stroke width double strokeWidth = mStrokeWidth; if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyStrokeWidth ) ) { context.setOriginalValueVariable( mStrokeWidth ); strokeWidth = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::PropertyStrokeWidth, context.renderContext().expressionContext(), mStrokeWidth ); } if ( mStrokeWidthUnit == QgsUnitTypes::RenderMillimeters ) { strokeWidth *= strokeWidth; } //fill color QColor fc = mColor; if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyFillColor ) ) { context.setOriginalValueVariable( QgsSymbolLayerUtils::encodeColor( mColor ) ); fc = mDataDefinedProperties.valueAsColor( QgsSymbolLayer::PropertyFillColor, context.renderContext().expressionContext(), mColor ); } //stroke color QColor oc = mStrokeColor; if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyStrokeColor ) ) { context.setOriginalValueVariable( QgsSymbolLayerUtils::encodeColor( mStrokeColor ) ); oc = mDataDefinedProperties.valueAsColor( QgsSymbolLayer::PropertyStrokeColor, context.renderContext().expressionContext(), mStrokeColor ); } //symbol name QString symbolName = mSymbolName; if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyName ) ) { context.setOriginalValueVariable( mSymbolName ); symbolName = mDataDefinedProperties.valueAsString( QgsSymbolLayer::PropertyName, context.renderContext().expressionContext(), mSymbolName ); } //offset double offsetX = 0; double offsetY = 0; markerOffset( context, offsetX, offsetY ); QPointF off( offsetX, offsetY ); //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle) double rotation = 0.0; if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyAngle ) ) { context.setOriginalValueVariable( mAngle ); rotation = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::PropertyAngle, context.renderContext().expressionContext(), mAngle ) + mLineAngle; } else if ( !qgsDoubleNear( mAngle + mLineAngle, 0.0 ) ) { rotation = mAngle + mLineAngle; } rotation = -rotation; //rotation in Qt is counterclockwise if ( rotation ) off = _rotatedOffset( off, rotation ); QTransform t; t.translate( shift.x() + offsetX, shift.y() + offsetY ); if ( !qgsDoubleNear( rotation, 0.0 ) ) t.rotate( rotation ); double halfWidth = symbolWidth / 2.0; double halfHeight = symbolHeight / 2.0; if ( symbolName == QLatin1String( "circle" ) ) { if ( qgsDoubleNear( halfWidth, halfHeight ) ) { QgsPoint pt( t.map( QPointF( 0, 0 ) ) ); e.writeFilledCircle( layerName, oc, pt, halfWidth ); } else { QgsPointSequence line; double stepsize = 2 * M_PI / 40; for ( int i = 0; i < 39; ++i ) { double angle = stepsize * i; double x = halfWidth * std::cos( angle ); double y = halfHeight * std::sin( angle ); line << QgsPoint( t.map( QPointF( x, y ) ) ); } //close ellipse with first point line << line.at( 0 ); if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( QgsRingSequence() << line, layerName, QStringLiteral( "SOLID" ), fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( line, layerName, QStringLiteral( "CONTINUOUS" ), oc, strokeWidth ); } } else if ( symbolName == QLatin1String( "rectangle" ) ) { QgsPointSequence p; p << QgsPoint( t.map( QPointF( -halfWidth, -halfHeight ) ) ) << QgsPoint( t.map( QPointF( halfWidth, -halfHeight ) ) ) << QgsPoint( t.map( QPointF( halfWidth, halfHeight ) ) ) << QgsPoint( t.map( QPointF( -halfWidth, halfHeight ) ) ); p << p[0]; if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( QgsRingSequence() << p, layerName, QStringLiteral( "SOLID" ), fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( p, layerName, QStringLiteral( "CONTINUOUS" ), oc, strokeWidth ); return true; } else if ( symbolName == QLatin1String( "cross" ) && mPen.style() != Qt::NoPen ) { e.writePolyline( QgsPointSequence() << QgsPoint( t.map( QPointF( -halfWidth, 0 ) ) ) << QgsPoint( t.map( QPointF( halfWidth, 0 ) ) ), layerName, QStringLiteral( "CONTINUOUS" ), oc, strokeWidth ); e.writePolyline( QgsPointSequence() << QgsPoint( t.map( QPointF( 0, halfHeight ) ) ) << QgsPoint( t.map( QPointF( 0, -halfHeight ) ) ), layerName, QStringLiteral( "CONTINUOUS" ), oc, strokeWidth ); return true; } else if ( symbolName == QLatin1String( "triangle" ) ) { QgsPointSequence p; p << QgsPoint( t.map( QPointF( -halfWidth, -halfHeight ) ) ) << QgsPoint( t.map( QPointF( halfWidth, -halfHeight ) ) ) << QgsPoint( t.map( QPointF( 0, halfHeight ) ) ); p << p[0]; if ( mBrush.style() != Qt::NoBrush ) e.writePolygon( QgsRingSequence() << p, layerName, QStringLiteral( "SOLID" ), fc ); if ( mPen.style() != Qt::NoPen ) e.writePolyline( p, layerName, QStringLiteral( "CONTINUOUS" ), oc, strokeWidth ); return true; } return false; //soon... }
UBRubberBand::enm_resizingMode UBRubberBand::determineResizingMode(QPoint pos) { if (mMouseIsPressed) return mResizingMode; QRect resizerTop (mResizingBorderHeight , 0 , rect().width()-2*mResizingBorderHeight, mResizingBorderHeight ); QRect resizerBottom (mResizingBorderHeight , rect().height() - mResizingBorderHeight, rect().width()-2*mResizingBorderHeight, mResizingBorderHeight ); QRect resizerLeft (0 , mResizingBorderHeight , mResizingBorderHeight , rect().height() - 2*mResizingBorderHeight); QRect resizerRight (rect().width()-mResizingBorderHeight, mResizingBorderHeight , mResizingBorderHeight , rect().height() - 2*mResizingBorderHeight); QRect resizerTopLeft (0 , 0 , mResizingBorderHeight, mResizingBorderHeight); QRect resizerTopRight (rect().width()-mResizingBorderHeight, 0 , mResizingBorderHeight, mResizingBorderHeight); QRect resizerBottomLeft (0 , rect().height() - mResizingBorderHeight, mResizingBorderHeight, mResizingBorderHeight); QRect resizerBottomRight(rect().width()-mResizingBorderHeight, rect().height() - mResizingBorderHeight, mResizingBorderHeight, mResizingBorderHeight); enm_resizingMode resizingMode; QTransform cursorTransrofm; if (resizerTop.contains(pos)) { resizingMode = Top; cursorTransrofm.rotate(90); } else if (resizerBottom.contains(pos)) { resizingMode = Bottom; cursorTransrofm.rotate(90); } else if (resizerLeft.contains(pos)) { resizingMode = Left; } else if (resizerRight.contains(pos)) { resizingMode = Right; } else if (resizerTopLeft.contains(pos)) { resizingMode = TopLeft; cursorTransrofm.rotate(45); } else if (resizerTopRight.contains(pos)) { resizingMode = TopRight; cursorTransrofm.rotate(-45); } else if (resizerBottomLeft.contains(pos)) { resizingMode = BottomLeft; cursorTransrofm.rotate(-45); } else if (resizerBottomRight.contains(pos)) { resizingMode = BottomRight; cursorTransrofm.rotate(45); } else resizingMode = None; if (None != resizingMode) { QPixmap pix(":/images/cursors/resize.png"); QCursor resizeCursor = QCursor(pix.transformed(cursorTransrofm, Qt::SmoothTransformation), pix.width() / 2, pix.height() / 2); setCursor(resizeCursor); } else unsetCursor(); return resizingMode; }