Trabalhar com Transparência em PostScript | C++

Adicionar transparência no documento PS

O PostScript não suporta transparência na pintura de objetos gráficos vetoriais. No entanto, as imagens translúcidas (parcialmente transparentes) podem ser renderizadas como um conjunto de pixéis totalmente transparentes e totalmente opacos. Estas imagens são chamadas de máscaras.

A biblioteca Aspose.Page para C++ oferece um método que adiciona a imagem transparente ao documento PS. Para pintar gráficos vectoriais: formas ou texto, oferecemos “pseudotransparência”.

“Pseudotransparência” é um processo de palidez de cor com um componente Alfa inferior a 255. É conseguido pela combinação específica dos componentes Vermelho, Verde e Azul com um componente Alfa.

“Pseudotransparência”, claro, não nos permite ver a camada colorida inferior por baixo da camada transparente superior, mas cria uma ilusão de transparência se a camada inferior for branca.

Adicionar imagem transparente num documento PS

Como já referimos anteriormente, as imagens transparentes podem ser adicionadas ao documento PS como uma máscara e a biblioteca Aspose.Page para C++ oferece para este efeito o método AddTransparentImage(). Este método reconhece se a imagem é totalmente opaca, totalmente transparente ou translúcida. Se for totalmente opaca, é adicionada como a imagem opaca no método AddImage(); se for totalmente transparente, não é adicionada ao documento; se for a imagem translúcida, é adicionada como uma máscara de imagem PostScript.

No exemplo abaixo, demonstramos a diferença entre adicionar uma imagem transparente num documento PS com AddImage() e AddTransparentImage(). Para ver a imagem branca translúcida, definimos a cor de fundo da página como não branca.

Para adicionar qualquer imagem a um novo PsDocument com a biblioteca Aspose.Page para C++, neste exemplo, seguimos os seguintes passos:

  1. Crie um fluxo de saída para o ficheiro PS resultante.
  2. Crie um objeto PsSaveOptions com as opções padrão. Altere a cor de fundo, se necessário.
  3. Crie um PsDocument de 1 página com um fluxo de saída já criado e opções de guardar.
  4. Crie um novo estado gráfico.
  5. Crie um Bitmap a partir do ficheiro de imagem.
  6. Crie a transformação necessária para a imagem.
  7. Adicione a imagem ao PsDocument como uma imagem totalmente opaca (utilizando o método AddImage()) se tivermos a certeza de que a imagem é opaca ou adicione uma como uma imagem transparente (utilizando o método AddTransparentImage()) se não tivermos a certeza de que a imagem é opaca.
  8. Saia do estado gráfico atual para o nível superior.
  9. Feche a página.
  10. Guarde o documento.
 1    // The path to the documents directory.
 2    System::String dataDir = RunExamples::GetDataDir_WorkingWithTransparency();
 3    
 4    //Create output stream for PostScript document
 5    {
 6        System::SharedPtr<System::IO::Stream> outPsStream = System::MakeObject<System::IO::FileStream>(dataDir + u"AddTransparentImage_outPS.ps", System::IO::FileMode::Create);
 7        // Clearing resources under 'using' statement
 8        System::Details::DisposeGuard<1> __dispose_guard_2({ outPsStream});
 9        // ------------------------------------------
10        
11        try
12        {
13            //Create save options with A4 size
14            System::SharedPtr<PsSaveOptions> options = System::MakeObject<PsSaveOptions>();
15            //Set page's background color to see white image on it's own transparent background
16            options->set_BackgroundColor(System::Drawing::Color::FromArgb(211, 8, 48));
17            
18            // Create new 1-paged PS Document
19            System::SharedPtr<PsDocument> document = System::MakeObject<PsDocument>(outPsStream, options, false);
20            
21            
22            document->WriteGraphicsSave();
23            document->Translate(20.0f, 100.0f);
24            
25            //Create bitmap from translucent image file
26            {
27                System::SharedPtr<System::Drawing::Bitmap> image = System::MakeObject<System::Drawing::Bitmap>(dataDir + u"mask1.png");
28                // Clearing resources under 'using' statement
29                System::Details::DisposeGuard<1> __dispose_guard_0({ image});
30                // ------------------------------------------
31                
32                try
33                {
34                    //Add this image to document as usual opaque RGB image
35                    document->DrawImage(image, System::MakeObject<System::Drawing::Drawing2D::Matrix>(1.0f, 0.0f, 0.0f, 1.0f, 100.0f, 0.0f), System::Drawing::Color::Empty);
36                }
37                catch(...)
38                {
39                    __dispose_guard_0.SetCurrentException(std::current_exception());
40                }
41            }
42            
43            //Again create bitmap from the same image file
44            {
45                System::SharedPtr<System::Drawing::Bitmap> image = System::MakeObject<System::Drawing::Bitmap>(dataDir + u"mask1.png");
46                // Clearing resources under 'using' statement
47                System::Details::DisposeGuard<1> __dispose_guard_1({ image});
48                // ------------------------------------------
49                
50                try
51                {
52                    //Add this image to document as transparent image image
53                    document->DrawTransparentImage(image, System::MakeObject<System::Drawing::Drawing2D::Matrix>(1.0f, 0.0f, 0.0f, 1.0f, 350.0f, 0.0f), 255);
54                }
55                catch(...)
56                {
57                    __dispose_guard_1.SetCurrentException(std::current_exception());
58                }
59            }
60            
61            document->WriteGraphicsRestore();
62            
63            //Close current page
64            document->ClosePage();
65            
66            //Save the document
67            document->Save();
68        }
69        catch(...)
70        {
71            __dispose_guard_2.SetCurrentException(std::current_exception());
72        }
73    }

Veja como trabalhar com transparência em documentos PS em .NET ou Java.

O resultado da execução deste código é o seguinte:

Adicionar Imagem Transparente

Adicionar objeto gráfico vetorial transparente

Anteriormente, escrevemos que a biblioteca Aspose. Page para C++ utiliza um algoritmo de paleta para formas e texto transparentes, a que chamamos “pseudo-transparência”. No exemplo abaixo, demonstramos a diferença entre duas formas pintadas com a mesma cor, mas na primeira forma sem a componente Alfa e no segundo caso com a componente Alfa.

 1    // The path to the documents directory.
 2    System::String dataDir = RunExamples::GetDataDir_WorkingWithTransparency();
 3    
 4    //Create output stream for PostScript document
 5    {
 6        System::SharedPtr<System::IO::Stream> outPsStream = System::MakeObject<System::IO::FileStream>(dataDir + u"ShowPseudoTransparency_outPS.ps", System::IO::FileMode::Create);
 7        // Clearing resources under 'using' statement
 8        System::Details::DisposeGuard<1> __dispose_guard_0({ outPsStream});
 9        // ------------------------------------------
10        
11        try
12        {
13            //Create save options with A4 size
14            System::SharedPtr<PsSaveOptions> options = System::MakeObject<PsSaveOptions>();
15            
16            // Create new 1-paged PS Document
17            System::SharedPtr<PsDocument> document = System::MakeObject<PsDocument>(outPsStream, options, false);
18            
19            float offsetX = 50.0f;
20            float offsetY = 100.0f;
21            float width = 200.0f;
22            float height = 100.0f;
23            
24            ///////////////////////////////// Create rectangle with opaque gradient fill /////////////////////////////////////////////////////////
25            System::SharedPtr<System::Drawing::Drawing2D::GraphicsPath> path = System::MakeObject<System::Drawing::Drawing2D::GraphicsPath>();
26            path->AddRectangle(System::Drawing::RectangleF(offsetX, offsetY, width, height));
27            
28            System::SharedPtr<System::Drawing::Drawing2D::LinearGradientBrush> opaqueBrush = System::MakeObject<System::Drawing::Drawing2D::LinearGradientBrush>(System::Drawing::RectangleF(0.0f, 0.0f, 200.0f, 100.0f), System::Drawing::Color::FromArgb(0, 0, 0), System::Drawing::Color::FromArgb(40, 128, 70), 0.f);
29            System::SharedPtr<System::Drawing::Drawing2D::Matrix> brushTransform = System::MakeObject<System::Drawing::Drawing2D::Matrix>(width, 0.0f, 0.0f, height, offsetX, offsetY);
30            opaqueBrush->set_Transform(brushTransform);
31            System::SharedPtr<GradientBrush> gradientBrush = System::MakeObject<GradientBrush>(opaqueBrush);
32            gradientBrush->set_WrapMode(System::Drawing::Drawing2D::WrapMode::Clamp);
33            
34            document->SetPaint(gradientBrush);
35            document->Fill(path);
36            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
37            
38            offsetX = 350.0f;
39            
40            ///////////////////////////////// Create rectangle with translucent gradient fill ///////////////////////////////////////////////////
41            //Create graphics path from the first rectangle
42            path = System::MakeObject<System::Drawing::Drawing2D::GraphicsPath>();
43            path->AddRectangle(System::Drawing::RectangleF(offsetX, offsetY, width, height));
44            
45            //Create linear gradient brush colors which transparency are not 255, but 150 and 50. So it are translucent.
46            System::SharedPtr<System::Drawing::Drawing2D::LinearGradientBrush> translucentBrush = System::MakeObject<System::Drawing::Drawing2D::LinearGradientBrush>(System::Drawing::RectangleF(0.0f, 0.0f, width, height), System::Drawing::Color::FromArgb(150, 0, 0, 0), System::Drawing::Color::FromArgb(50, 40, 128, 70), 0.f);
47            //Create a transform for brush.
48            brushTransform = System::MakeObject<System::Drawing::Drawing2D::Matrix>(width, 0.0f, 0.0f, height, offsetX, offsetY);
49            //Set transform
50            translucentBrush->set_Transform(brushTransform);
51            //Create GradientBrush object containing the linear gradient brush
52            gradientBrush = System::MakeObject<GradientBrush>(translucentBrush);
53            gradientBrush->set_WrapMode(System::Drawing::Drawing2D::WrapMode::Clamp);
54            //Set paint
55            document->SetPaint(gradientBrush);
56            //Fill the rectangle
57            document->Fill(path);
58            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
59            
60            //Close current page
61            document->ClosePage();
62            
63            //Save the document
64            document->Save();
65        }
66        catch(...)
67        {
68            __dispose_guard_0.SetCurrentException(std::current_exception());
69        }
70    }

Veja como trabalhar com transparência em documentos PS em .NET ou Java.

O resultado da execução deste código é apresentado como

Mostrar Pseudo-Transparência

Pode descarregar exemplos e ficheiros de dados do GitHub.

Have any questions about Aspose.Page?



Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.