Advertisement
Guest User

Untitled

a guest
Apr 19th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. void QgisApp::saveMapAsImage()
  3. {
  4.   QPair< QString, QString> myFileNameAndFilter = QgisGui::getSaveAsImageName( this, tr( "Choose a file name to save the map image as" ) );
  5.   if ( myFileNameAndFilter.first != QLatin1String( "" ) )
  6.   {
  7.     QgsMapSettings ms = QgsMapSettings();
  8.  
  9.     int dpi = 300;
  10.     QSize size = mMapCanvas->size() * (dpi / 90);
  11.  
  12.     ms.setDestinationCrs( QgsProject::instance()->crs() );
  13.     ms.setExtent( mMapCanvas->extent() );
  14.     ms.setOutputSize( size );
  15.     ms.setOutputDpi( dpi );
  16.     ms.setBackgroundColor( Qt::white );
  17.     ms.setRotation( mMapCanvas->rotation() );
  18.     ms.setLayers( mMapCanvas->layers() );
  19.  
  20.     QImage img = QImage( size, QImage::Format_ARGB32 );
  21.     QPainter p( &img );
  22.  
  23.     QgsMapRendererCustomPainterJob r( ms, &p );
  24.     r.renderSynchronously();
  25.  
  26.     QgsRenderContext context = QgsRenderContext::fromMapSettings( ms );
  27.     context.setPainter( &p );
  28.      
  29.     QList< QgsAnnotation * > annotations = QgsProject::instance()->annotationManager()->annotations();
  30.     Q_FOREACH ( QgsAnnotation *annotation, annotations )
  31.     {
  32.       if ( !annotation || !annotation->isVisible() )
  33.       {
  34.         continue;
  35.       }
  36.       if ( annotation->mapLayer() && !mMapCanvas->layers().contains( annotation->mapLayer() ) )
  37.       {
  38.         continue;
  39.       }
  40.  
  41.       context.painter()->save();
  42.       context.painter()->setRenderHint( QPainter::Antialiasing, context.flags() & QgsRenderContext::Antialiasing );
  43.  
  44.       double itemX, itemY;
  45.       if ( annotation->hasFixedMapPosition() )
  46.       {  
  47.         itemX = annotation->mapPosition().x();
  48.         itemY = annotation->mapPosition().y();
  49.       }
  50.       else
  51.       {
  52.         itemX = annotation->relativePosition().x() * size.width();
  53.         itemY = annotation->relativePosition().y() * size.height();
  54.       }
  55.  
  56.       //TODO: deal with CRS transform?
  57.      
  58.       context.painter()->translate( itemX, itemY );
  59.  
  60.       annotation->render( context );
  61.       context.painter()->restore();
  62.     }
  63.  
  64.     p.end();
  65.     img.save( myFileNameAndFilter.first, myFileNameAndFilter.second.toLocal8Bit().data() );
  66.     statusBar()->showMessage( tr( "Saved map image to %1" ).arg( myFileNameAndFilter.first ) );
  67.   }
  68.  
  69. } // saveMapAsImage
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement