Compartilhar via


Desenhar gráficos em um OM XPS

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

Para desenhar elementos 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 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 interfaceIXpsOMGeometry, que contém uma coleção de interfaces IXpsOMGeometryFigure e, opcionalmente, uma interface IXpsOMMatrixTransform. Você pode usar qualquer interface que herda 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ão usados 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 interfaceIXpsOMGeometry. Em seguida, ele cria a interfaceIXpsOMGeometryFigure que especifica a forma da figura e adiciona a figura à interface IXpsOMGeometry. O exemplo cria um retângulo especificado pelo 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 para verdadeiro indica que o retângulo é 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 path 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 interfaceIXpsOMPath. Para o benefício de usuários com deficiência visual, use os métodos SetAccessibilityShortDescription e SetAccessibilityLongDescript ion 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 interfaceIXpsOMSolidColorBrushcomo pincel de preenchimento e pincel de traço para o caminho. Além da interface IXpsOMSolidColorBrush, você pode usar um IXpsOMGradientBrush, IXpsOMImageBrush ou interface de IXpsOMVisualBrush.

O traço é a linha que pode ser desenhada ao redor do perímetro da figura. O de Especificação de Papel XML 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 interfaceIXpsOMPath:

próximas etapas

navegar no de OM do XPS

gravar texto em um de OM XPS

colocar imagens em um de OM XPS

gravar um OM XPS em um documento XPS

imprimir um de OM XPS

usado nesta página

IOpcPartUri

IXpsOMGeometry

IXpsOMGeometryFigure

IXpsOMGeometryFigureCollection

IXpsOMObjectFactory

IXpsOMPage

IXpsOMPath

IXpsOMSolidColorBrush

IXpsOMVisualCollection

para obter mais informações

inicializar um de OM XPS

de referência da API de Documentos XPS

de especificação de papel XML