Compartilhar via


Desenhar gráficos em um OM do XPS

Esta página descreve como desenhar gráficos em um OM do XPS.

Para desenhar gráficos baseados em vetor em uma página, instancie uma interface IXpsOMPath, preencha-a com o conteúdo desejado e adicione-a à lista de objetos visuais da página ou da tela. Uma interface IXpsOMPath contém essas propriedades de uma forma baseada em vetor como a estrutura de tópicos, a cor de preenchimento, o estilo de linha e a cor da linha. A forma do caminho é especificada por uma interface IXpsOMGeometry, que contém uma coleção de interfaces IXpsOMGeometryFigure e, opcionalmente, uma interface IXpsOMMatrixTransform. Você pode usar qualquer interface herdada da interface IXpsOMBrush para preencher o perímetro do caminho e o interior da forma descrita pelo caminho.

Antes de usar os exemplos de código a seguir em seu programa, leia o aviso de isenção de responsabilidade nas Tarefas comuns de programação de documentos XPS.

Exemplo de código

O exemplo de código a seguir cria um caminho simples que descreve um retângulo que é preenchido com uma única cor.

Criar o traço e os pincéis de preenchimento

A primeira seção do exemplo de código cria o IXpsOMSolidColorBrush que será usado para preencher o objeto de caminho.

    HRESULT               hr = S_OK;

    XPS_COLOR             xpsColor;
    IXpsOMSolidColorBrush *xpsFillBrush = NULL;
    IXpsOMSolidColorBrush *xpsStrokeBrush = NULL;

    // Set the fill brush color to RED.
    xpsColor.colorType = XPS_COLOR_TYPE_SRGB;
    xpsColor.value.sRGB.alpha = 0xFF;
    xpsColor.value.sRGB.red = 0xFF;
    xpsColor.value.sRGB.green = 0x00;
    xpsColor.value.sRGB.blue = 0x00;

    // Use the object factory to create the brush.
    hr = xpsFactory->CreateSolidColorBrush( 
        &xpsColor,
        NULL,          // color profile resource
        &xpsFillBrush);
    // The color profile resource parameter is NULL because
    //  this color type does not use a color profile resource.

    // Set the stroke brush color to BLACK.
    xpsColor.colorType = XPS_COLOR_TYPE_SRGB;
    xpsColor.value.sRGB.alpha = 0xFF;
    xpsColor.value.sRGB.red = 0x00;
    xpsColor.value.sRGB.green = 0x00;
    xpsColor.value.sRGB.blue = 0x00;

    // Use the object factory to create the brush.
    hr = xpsFactory->CreateSolidColorBrush( 
            &xpsColor,
            NULL, // This color type does not use a color profile resource.
            &xpsStrokeBrush);

    // The brushes are released below after they have been used.

Definir a forma

A segunda seção do exemplo de código cria a interface IXpsOMGeometry. Em seguida, ele cria a interface IXpsOMGeometryFigure que especifica a forma da figura e adiciona a figura à interface IXpsOMGeometry. O exemplo cria um retângulo especificado por rect. Os segmentos devem ser definidos para apenas três dos quatro lados do retângulo. O perímetro da forma, o retângulo nesse caso, começa do ponto inicial e se estende conforme definido pelos segmentos da figura de geometria. Definir a propriedade IsClosed como TRUE indica que o retângulo está fechado adicionando um segmento adicional que conecta o final do último segmento ao ponto inicial.

    // rect is initialized outside of the sample and 
    //  contains the coordinates of the rectangular geometry to create.
    XPS_RECT                            rect = {0,0,100,100};       

    HRESULT                             hr = S_OK;
    IXpsOMGeometryFigure                *rectFigure;
    IXpsOMGeometry                      *imageRectGeometry;
    IXpsOMGeometryFigureCollection      *geomFigureCollection;

    // Define the start point and create an empty figure.
    XPS_POINT                           startPoint = {rect.x, rect.y};
    hr = xpsFactory->CreateGeometryFigure( &startPoint, &rectFigure );
    // Define the segments of the geometry figure.
    //  First, define the type of each segment.
    XPS_SEGMENT_TYPE segmentTypes[3] = {
        XPS_SEGMENT_TYPE_LINE,  // each segment is a straight line
        XPS_SEGMENT_TYPE_LINE, 
        XPS_SEGMENT_TYPE_LINE
    };

    // Define the x and y coordinates of each corner of the figure
    //  the start point has already been defined so only the 
    //  remaining three corners need to be defined.
    FLOAT segmentData[6] = {
        rect.x,                (rect.y + rect.height),
        (rect.x + rect.width), (rect.y + rect.height), 
        (rect.x + rect.width), rect.y 
    };

    // Describe if the segments are stroked (that is if the segment lines
    //  should be drawn as a line).
    BOOL segmentStrokes[3] = {
        TRUE, TRUE, TRUE // Yes, draw each of the segment lines.
    };

    // Add the segment data to the figure.
    hr = rectFigure->SetSegments(
                        3, 
                        6, 
                        segmentTypes, 
                        segmentData, 
                        segmentStrokes);

    // Set the closed and filled properties of the figure.
    hr = rectFigure->SetIsClosed( TRUE );
    hr = rectFigure->SetIsFilled( TRUE );
 
    // Create the geometry object.
    hr = xpsFactory->CreateGeometry( &imageRectGeometry );
    
    // Get a pointer to the figure collection interface of the geometry...
    hr = imageRectGeometry->GetFigures( &geomFigureCollection );

    // ...and then add the figure created above to this geometry.
    hr = geomFigureCollection->Append( rectFigure );
    // If not needed for anything else, release the rectangle figure.
    rectFigure->Release();

    // when done adding figures, release the figure collection. 
    geomFigureCollection->Release();

    //  When done with the geometry object, release the object.
    // imageRectGeometry->Release();
    //  In this case, imageRectGeometry is used in the next sample
    //  so the geometry object is not released, yet.
    

Criar o caminho e adicioná-lo à coleção visual

A seção final deste exemplo de código cria e configura o objeto de caminho e, em seguida, adiciona-o à lista de objetos visuais da página.

    HRESULT                    hr = S_OK;
    // The page interface pointer is initialized outside of this sample.
    IXpsOMPath                *rectPath = NULL;
    IXpsOMVisualCollection    *pageVisuals = NULL;

    // Create the new path object.
    hr = xpsFactory->CreatePath( &rectPath );

    // Add the geometry to the path.
    //  imageRectGeometry is initialized outside of this example.
    hr = rectPath->SetGeometryLocal( imageRectGeometry );

    // Set the short description of the path to provide
    //  a textual description of the object for accessibility.
    hr = rectPath->SetAccessibilityShortDescription( L"Red Rectangle" );
    
    // Set the fill and stroke brushes to use the brushes 
    //  created in the first section.
    hr = rectPath->SetFillBrushLocal( xpsFillBrush );
    hr = rectPath->SetStrokeBrushLocal( xpsStrokeBrush);

    // Get the visual collection of this page and add this path to it.
    hr = xpsPage->GetVisuals( &pageVisuals );
    hr = pageVisuals->Append( rectPath );
    // If not needed for anything else, release the rectangle path.
    rectPath->Release();
    
    // When done with the visual collection, release it.
    pageVisuals->Release();

    // When finished with the brushes, release the interface pointers.
    if (NULL != xpsFillBrush) xpsFillBrush->Release();
    if (NULL != xpsStrokeBrush) xpsStrokeBrush->Release();

    // When done with the geometry interface, release it.
    imageRectGeometry->Release();

    // When done with the path interface, release it.
    rectPath->Release();

Práticas Recomendadas

Adicione uma descrição textual da forma especificada pela interface IXpsOMPath. Para o benefício de usuários com deficiência visual, use os métodos SetAccessibilityShortDescription e SetAccessibilityLongDescription para fornecer conteúdo textual para recursos de suporte de acessibilidade, como leitores de tela.

Informações adicionais

O exemplo de código nesta página usa uma interface IXpsOMSolidColorBrush como pincel de preenchimento e pincel de traço para o caminho. Além da interface IXpsOMSolidColorBrush, você pode usar uma interface IXpsOMGradientBrush, IXpsOMImageBrush ou IXpsOMVisualBrush.

O traço é a linha que pode ser desenhada ao redor do perímetro da figura. A XML Paper Specification dá suporte a vários estilos de linha de traço diferentes. Para especificar o estilo de linha de traço, defina as propriedades de traço com os seguintes métodos da interface IXpsOMPath:

Próximas Etapas 

Navegar pelo OM do XPS

Gravar texto em um OM do XPS

Colocar imagens em um OM do XPS

Gravar um OM do XPS em um documento do XPS

Imprimir um OM do XPS

Usado nesta página

IOpcPartUri

IXpsOMGeometry

IXpsOMGeometryFigure

IXpsOMGeometryFigureCollection

IXpsOMObjectFactory

IXpsOMPage

IXpsOMPath

IXpsOMSolidColorBrush

IXpsOMVisualCollection

Para obter mais informações

Inicializar um OM do XPS

Referência da API de Documentos do XPS

XML Paper Specification