Dibujar gráficos en un OM XPS

En esta página se describe cómo dibujar gráficos en un OM XPS.

Para dibujar gráficos basados en vectores en una página, cree una instancia de una interfaz de IXpsOMPath, llénela con el contenido deseado y agréguela a la lista de objetos visuales de la página o lienzo. Una interfaz IXpsOMPath contiene estas propiedades de una forma basada en vectores como contorno, color de relleno, estilo de línea y color de línea. La forma de la ruta de acceso se especifica mediante una interfazIXpsOMGeometry, que contiene una colección de interfaces IXpsOMGeometryFigurey, opcionalmente, una interfaz IXpsOMMatrixTransform. Puede usar cualquier interfaz que herede de la interfaz IXpsOMBrush para rellenar el perímetro de la ruta de acceso y el interior de la forma descrita por la ruta de acceso.

Antes de usar los siguientes ejemplos de código en el programa, lea la declinación de responsabilidades en Common XPS Document Programming Tasks.

Ejemplo de código

En el ejemplo de código siguiente se crea una ruta de acceso sencilla que describe un rectángulo que se rellena con un único color.

Crear el trazo y los pinceles de relleno

La primera sección del ejemplo de código crea el IXpsOMSolidColorBrush que se usará para rellenar el objeto path.

    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.

Definición de la forma

La segunda sección del ejemplo de código crea la interfaz IXpsOMGeometry. A continuación, crea la interfaz IXpsOMGeometryFigure que especifica la forma de la figura y agrega la figura a la interfaz IXpsOMGeometry. En el ejemplo se crea un rectángulo especificado por rect. Los segmentos deben definirse solo para tres de los cuatro lados del rectángulo. El perímetro de la forma, el rectángulo en este caso, comienza desde el punto de inicio y se extiende según lo definido por los segmentos de la figura de geometría. Si se establece la propiedad IsClosed en TRUE, se indica que el rectángulo está cerrado agregando un segmento adicional que conecta el final del último segmento al punto de inicio.

    // 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.
    

Cree la ruta de acceso y agréguela a la colección visual

La sección final de este ejemplo de código crea y configura el objeto path y, a continuación, lo agrega a la lista de objetos visuales de la 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();

Procedimientos recomendados

Agregue una descripción textual de la forma especificada por la interfaz IXpsOMPath. Para beneficiarse de los usuarios con discapacidades visuales, use los métodos SetAccessibilityShortDescription y SetAccessibilityLongDescription para proporcionar contenido textual para características de compatibilidad con accesibilidad, como lectores de pantalla.

Información adicional

En el ejemplo de código de esta página se usa una interfaz IXpsOMSolidColorBrush como pincel de relleno y pincel de trazo para la ruta de acceso. Además de la interfaz IXpsOMSolidColorBrush, puede usar una interfaz IXpsOMGradientBrush, IXpsOMImageBrush, o IXpsOMVisualBrush.

El trazo es la línea que se puede dibujar alrededor del perímetro de la figura. El XML Paper Specification admite muchos estilos de línea de trazo diferentes. Para especificar el estilo de línea de trazo, establezca las propiedades de trazo con los métodos siguientes de la interfaz IXpsOMPath :

Pasos siguientes

Navegar por el OM XPS

Escribir texto en un OM XPS

Colocar imágenes en un OM XPS

Escribir un OM XPS en un documento XPS

Imprimir un OM XPS

Se usa en esta página

IOpcPartUri

IXpsOMGeometry

IXpsOMGeometryFigure

IXpsOMGeometryFigureCollection

IXpsOMObjectFactory

IXpsOMPage

IXpsOMPath

IXpsOMSolidColorBrush

IXpsOMVisualCollection

Para obtener más información

Inicializar un OM XPS

Referencia de la API de documentos XPS

XML Paper Specification