Text


DirectWrite

DirectX uses DirectWrite to draw text with specific properties such as: font, alignment, size, color, etc. To use DirectWrite you need to include the dwrite.h header file.
DirectX usa DirectWrite para dibujar texto con propiedades específicas tales como: fuente, alineación, tamaño, color, etc. Para usar DirectWrite usted necesita incluir el archivo de encabezado dwrite.h.

Direct2D

Direct2D provides high performance and high quality rendering for 2D drawing, bitmaps and text. It is hardware-accelerate and requires the d2d1.h header file and the d2d1_1.h header file. You need also to link with D2d1.lib.
Direct2D proporciona dibujo en dos dimensiones de alto desempeño y de alto calidad para figuras geométricas, mapas de bits y texto. Este acelerado por hardware y requiere el archivo de encabezado d2d1.h y el archivo de encabezado d2d1_1.h. Usted necesita también enlazar con D2d1.lib.

Problem 1
Create a Wintempla Window Applicaction called HelloDx to display some text using DirectWrite and Direct2D (observe that this is not a DirectX application). After creating the application, open Wintempla and double click anywhere in the editor to set the events Idle and Size as shown.
Cree una aplicación de Ventana usando Wintempla llamada HelloDx para desplegar un texto usando DirectWrite y Direct2D (observe que esta no es una aplicación de DirectX). Después de crear el programa, abra Wintempla y haga clic doble en cualquier parte del editor para fijar los eventos Idle y Size como se muestra.

Window_Idle

Window_Size

HelloDxRun

Step A
At the end of the stdafx.h file add the following code.
Al final del archivo stdafc.h agregué el siguiente código.

stdafx.h
...
//____________________________________________________ 1. DirectWrite
#include <dwrite.h>
#pragma comment(lib, "Dwrite.lib")
//____________________________________________________ 2. Direct2D
#include <d2d1.h>
#include <d2d1_1.h>
#pragma comment(lib, "D2d1.lib")


Step B
Edit the HelloDx.h file and the HelloDx.cpp file as shown. Do not forget to change the Message Loop at the top of the HelloDx.cpp file so that you can use the Window_Idle event.. In the same way, you may want to use the NULL_BRUSH instead of the regular window color.
Edite el archivo HelloDx.h y el archivo HelloDx.cpp como se muestra. No se olvide de cambiar el Message Loop en la parte de arriba del archivo HelloDx.cpp para poder usar el evento Window_Idle. De la misma forma, usted quisiera usar la NULL_BRUSH en lugar del color regular de la ventana.

HelloDx.h
#pragma once //______________________________________ HelloDx.h
#include "Resource.h"
class HelloDx: public Win::Window
{
public:
     HelloDx()
     {
          ::CoInitialize(NULL);
          x = 0.0f;
          y = 0.0f;
     }
     ~HelloDx()
     {
          ::CoUninitialize();
     }
     Sys::Stopwatch sw;
     Microsoft::WRL::ComPtr<IDWriteFactory> writeFactory;
     Microsoft::WRL::ComPtr<IDWriteTextFormat> textFormat;
     Microsoft::WRL::ComPtr<ID2D1Factory> d2DFactory;
     Microsoft::WRL::ComPtr<ID2D1HwndRenderTarget> renderTarget;
     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> blackBrush;
     float x;
     float y;
     //
     void RenderScene();
     . . .
};

Hello.cpp
. . .
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE , LPTSTR cmdLine, int cmdShow){
     HelloDx app;
     app.CreateMainWindow(L"HelloDx", cmdShow, IDI_HelloDx, NULL, (HBRUSH)::GetStockObject(NULL_BRUSH), hInstance);
     return app.MessageLoopIdle(IDC_HelloDx);
}

void HelloDx::Window_Open(Win::Event& e)
{
     HRESULT hr;
     Com::Exception ex;
     try
     {
          //___________________________________________________________________________________ 1. Create a 2DFactory
          hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, d2DFactory.GetAddressOf());
          ex.ok(L"D2D1CreateFactory", hr);
          //___________________________________________________________________________________ 2. Create a WriteFactory
          hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), &writeFactory);
          ex.ok(L"DWriteCreateFactory", hr);
          //___________________________________________________________________________________ 3. Create a WriteTextFormat
          hr = writeFactory->CreateTextFormat(L"Arial", NULL, DWRITE_FONT_WEIGHT_REGULAR,
               DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 72.0f, L"en-us", &textFormat);
          ex.ok(L"writeFactory->CreateTextFormat", hr);
          //
          hr = textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
          ex.ok(L"textFormat->SetTextAlignment", hr);
          //
          hr = textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
          ex.ok(L"textFormat->SetParagraphAlignment", hr);
     }
     catch (Com::Exception& excep)
     {
          excep.Display(hWnd, L"HelloDx");
     }
}

void HelloDx::RenderScene()
{
     x += (float)(sw.GetSeconds() * 10.0);
     y += (float)(sw.GetSeconds() * 12.0);
     sw.Start();
     //
     renderTarget->SetTransform(D2D1::IdentityMatrix());
     renderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
     D2D1_RECT_F layoutRect = D2D1::RectF(x, y, (float)width, (float)height);
     const wchar_t* message = L"I love DirectWrite!";
     renderTarget->DrawText(message, (int)wcslen(message), textFormat.Get(), layoutRect, blackBrush.Get());
}

void HelloDx::Window_Idle(Win::Event& e)
{
     // _______________________________________________________________________________ 1. Create Device resources
     if (renderTarget == nullptr)
     {
          // __________________________________________________________ 1.1. Create a render target
          D2D1_SIZE_U size = D2D1::SizeU(width, height);
          if (FAILED(d2DFactory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, size), &renderTarget))) return;
          // __________________________________________________________ 1.2. Create a black brush.
          blackBrush = nullptr; // Release previous resource
          if (FAILED(renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &blackBrush))) return;
     }
     // _______________________________________________________________________________ 2. RenderScene
     renderTarget->BeginDraw();
     RenderScene();
     if (renderTarget->EndDraw()==D2DERR_RECREATE_TARGET) renderTarget = nullptr;
}

void HelloDx::Window_Size(Win::Event& e)
{
     if (renderTarget != nullptr) renderTarget->Resize(D2D1::SizeU(width, height));
}



Problem 2
Using UML create a set of classes to implement the game of Pacman using DirectX. Do not forget that you may need to pass variables from the main class to each class.
Usando UML cree un conjunto de clases para implementar el juego de Pacman en DirectX. No se olvide que usted necesita pasar variables desde la clase principal a cada clase.

Problem 3
Create a Wintempla Window application called FastView to test Direct2D (observe that this project is not a DirectX application). After creating the application, open Wintempla and double click the on the GUI editor to select the events: KeyDown, Paint and Size.
Cree una aplicación de ventana de Wintempla llamada FastView para probar Direct2D (observe que este proyecto no es una aplicación de DirectX). Después de crear la aplicación, abra Wintempla y haga clic doble en el editor de la GUI para seleccionar los eventos: KeyDown, Paint y Size.

FasViewRun

FastViewEvents

FastViewKeyDown

Step A
Edit the stdafx.h file as shown.
Edite el archivo stdafx.h cómo se muestra.

stdafx.h
...
//____________________________________________________ 1. DirectWrite
#include <dwrite.h>
#pragma comment(lib, "Dwrite.lib")
//____________________________________________________ 2. Direct2D
#include <d2d1.h>
#include <d2d1_1.h>
#pragma comment(lib, "D2d1.lib")


Step B
Edit the FastView.h file and the FastView.cpp file as shown.
Edite el archivo FastView.h y el archivo FastView.cpp como se muestra.

FastView.h
#pragma once //______________________________________ FastView.h
#include "Resource.h"

class FastView: public Win::Window
{
public:
     FastView()
     {
          ::CoInitialize(NULL);
     }
     ~FastView()
     {
          ::CoUninitialize();
     }
     Microsoft::WRL::ComPtr<ID2D1Factory> d2DFactory;
     Microsoft::WRL::ComPtr<ID2D1HwndRenderTarget> renderTarget;
     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> blueBrush;
     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> blackBrush;
     //
     . . .
};


FastView.cpp
. . .
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE , LPTSTR cmdLine, int cmdShow){
     FastView app;

     //_______________________________________________________________ Option 1. Window
     //app.CreateMainWindow(L"FastView", cmdShow, IDI_FastView, NULL, (HBRUSH)(COLOR_WINDOW + 1), hInstance);

     //_______________________________________________________________ Option 2. Full Screen (Press Escape to close)
     app.CreateMainWindow(0, WS_POPUP | WS_VISIBLE, 0, 0, ::GetSystemMetrics(SM_CXSCREEN), ::GetSystemMetrics(SM_CYSCREEN),
          L"FastView", SW_NORMAL, IDI_FastView, NULL, (HBRUSH)::GetStockObject(NULL_BRUSH), hInstance);

     return app.MessageLoop(IDC_FastView);
}

void FastView::Window_Open(Win::Event& e)
{
     HRESULT hr;
     Com::Exception ex;
     try
     {
          //___________________________________________________________________________________ 1. Create a 2DFactory
          hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, d2DFactory.GetAddressOf());
          ex.ok(L"D2D1CreateFactory", hr);
     }
     catch (Com::Exception& excep)
     {
          excep.Display(hWnd, L"FastView");
     }
}

void FastView::Window_Paint(Win::Event& e)
{
     // _______________________________________________________________________________ 1. Create device resources
     if (renderTarget == nullptr)
     {
          // __________________________________________________ 1.1. Create a render target
          D2D1_SIZE_U size = D2D1::SizeU(width, height);
          if (FAILED(d2DFactory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, size), &renderTarget))) return;
          //__________________________________________________ 1.2. Create blue brush
          blueBrush = nullptr; // Release previous resource
          if (FAILED(renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Blue), &blueBrush))) return;
          //__________________________________________________ 1.3. Create black brush
          blackBrush = nullptr; // Release previous resource
          if (FAILED(renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &blackBrush))) return;
     }
     //_______________________________________________________________________________ 2. BeginDraw
     renderTarget->BeginDraw();
     renderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
     renderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
     //_______________________________________________________________________________ 3. Lines
     D2D1_SIZE_F size = renderTarget->GetSize();
     const int width = (int)(size.width);
     const int height = (int)(size.height);
     const int lineCount = 50;
     const FLOAT deltaX = width/(FLOAT)lineCount;
     const FLOAT deltaY = height/(FLOAT)lineCount;
     for (int i = 0; i<lineCount; i++)
     {
          renderTarget->DrawLine(D2D1::Point2F(0.0f, deltaY*i), D2D1::Point2F(deltaX*i + deltaX, size.height), blackBrush.Get(), 1.0f);
          renderTarget->DrawLine(D2D1::Point2F(deltaX*i, 0.0f), D2D1::Point2F(size.width, deltaY*i+deltaY), blackBrush.Get(), 1.0f);
     }
     //_______________________________________________________________________________ 4. Blue rectangle
     D2D1_RECT_F rect = D2D1::RectF(size.width/2- 50.0f, size.height/2- 50.0f, size.width/2 + 50.0f,size.height/2 + 50.0f);
     renderTarget->FillRectangle(&rect, blueBrush.Get());
     //_______________________________________________________________________________ 5. EndDraw
     if (renderTarget->EndDraw()==D2DERR_RECREATE_TARGET) renderTarget = nullptr;
     ::ValidateRect(hWnd, NULL);
}

void FastView::Window_Size(Win::Event& e)
{
     if (renderTarget != NULL) renderTarget->Resize(D2D1::SizeU(width, height));
}

void FastView::Window_KeyDown(Win::Event& e)
{
     switch (e.wParam)
     {
     case VK_ESCAPE:
          ::DestroyWindow(hWnd);
          break;
     }
}


CreateBitmap      Creates a D2D bitmap by copying from memory, or create uninitialized.  
CreateBitmapFromWicBitmapCreate a D2D bitmap by copying a WIC bitmap.
CreateSharedBitmapCreates a D2D bitmap by sharing bits from another resource. The bitmap must be compatible with the render target for the call to succeed. For example, an IWICBitmap can be shared with a software target, or a DXGI surface can be shared with a DXGI render target.
CreateBitmapBrushCreates a bitmap brush. The bitmap is scaled, rotated, skewed or tiled to fill or pen a geometry.
CreateSolidColorBrushCreates a color brush.
CreateGradientStopCollectionA gradient stop collection represents a set of stops in an ideal unit length. This is the source resource for a linear gradient and radial gradient brush.
CreateLinearGradientBrushCreates a linear gradient brush.
CreateRadialGradientBrushCreates a radial gradient brush.
CreateLayerCreates a layer resource that can be used on any target and which will resize under the covers if necessary.
CreateMeshCreates a 2D mesh.
FillMeshFill a mesh. Since meshes can only render aliased content, the render target antialiasing mode must be set to aliased.
DrawLineDraws a line using the specified stroke properties.
DrawRectangleDraws the border of a rectangleusing the specified stroke properties.
FillRectangleFills a rectangular area with a brush.
FillRoundedRectangleFills a rounded rectangular area with a brush.
DrawEllipseDraws an ellipse using the specified stroke properties.
FillEllipseFills an ellipse area with a brush.
DrawGeometryDraws a simple or complex geometry.
FillGeometryFills a simple or complex geometry.
FillOpacityMaskFill using the alpha channel of the supplied opacity mask bitmap. The brush opacity will be modulated by the mask. The render target antialiasing mode must be set to aliased.
DrawBitmapDraws a bitmap.
DrawTextDraws the text within the given layout rectangle and by default also snaps and clips it to the content bounds.
DrawTextLayoutDraw a snapped text layout object. Since the layout is not subsequently changed, this can be more efficient than DrawText when drawing the same layout repeatedly.
DrawGlyphRunDraws the specified glyphs.
SetTransformApplies the specified transform to the render target, replacing the existing transformation. All subsequent drawing operations occur in the transformed space.
GetTransformGets the current transform of the render target.
SetAntialiasModeSets the antialiasing mode of the render target. The antialiasing mode applies to all subsequent drawing operations, excluding text and glyph drawing operations. D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, D2D1_ANTIALIAS_MODE_ALIASED, D2D1_ANTIALIAS_MODE_FORCE_DWORD
GetAntialiasModeRetrieves the current antialiasing mode for non-text drawing operations.
SetTextAntialiasModeSpecifies the antialiasing mode to use for subsequent text and glyph drawing operations.
GetTextAntialiasModeGets the current antialiasing mode for text and glyph drawing operations.
SetTextRenderingParamsSpecifies text rendering options to be applied to all subsequent text and glyph drawing operations.
GetTextRenderingParamsRetrieves the render target's current text rendering options.
SetTagsSets a tag to correspond to the succeeding primitives. If an error occurs rendering a primitive, the tags can be returned from the Flush or EndDraw call.
GetTagsRetrieves the currently set tags. This does not retrieve the tags corresponding to any primitive that is in error.
PushLayerStarts a layer of drawing calls.
PopLayerEnds a layer that was defined with particular layer resources.
SaveDrawingStateGets the current drawing state and saves it into the supplied IDrawingStatckBlock.
RestoreDrawingStateCopies the state stored in the block interface.
PushAxisAlignedClipPushes a clip. The clip can be antialiased. The clip must be axis aligned. If the current world transform is not axis preserving, then the bounding box of the transformed clip rect will be used. The clip will remain in effect until a PopAxisAligned clip call is made.
PopAxisAlignedClipPops a clip.
ClearClears the drawing area to the specified color.
GetPixelFormatRetrieves the pixel format and alpha mode of the render target.
SetDpiSets the DPI on the render target. This results in the render target being interpreted to a different scale. Neither DPI can be negative. If zero is specified for both, the system DPI is chosen. If one is zero and the other unspecified, the DPI is not changed.
GetDpiReturns the current DPI from the target.
GetSizeReturns the size of the render target in DIPs.
GetPixelSizeReturns the size of the render target in pixels.
GetMaximumBitmapSizeReturns the maximum bitmap and render target size that is guaranteed to be supported by the render target.

Problem 4
Create a Wintempla Window application called MountainView to draw some objects using paths and beziers in Direct2D (observe that this project is not a DirectX application). After creating the application, open Wintempla and double click the on the GUI editor to select the events: KeyDown, Paint and Size. Edit the stdafx.file as in the previous problem.
Cree una aplicación de ventana de Wintempla llamada MountainView para dibujar algunos objetos usando paths y beziers in Direct2D (observe que este proyecto no es una aplicación de DirectX). Después de crear la aplicación, abra Wintempla y haga clic doble en el editor de la GUI para seleccionar los eventos: KeyDown, Paint y Size. Edite el archivo stdafx.h como en el problema anterior.

MountainViewRun

MountainView.h
#pragma once //______________________________________ MountainView.h
#include "Resource.h"
class MountainView: public Win::Window
{
public:
     MountainView()
     {
          ::CoInitialize(NULL);
     }
     ~MountainView()
     {
          ::CoUninitialize();
     }
     Microsoft::WRL::ComPtr<ID2D1Factory> d2DFactory;
     Microsoft::WRL::ComPtr<ID2D1HwndRenderTarget> renderTarget;
     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> greenBrush;
     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> blackBrush;
     Microsoft::WRL::ComPtr<ID2D1RadialGradientBrush> gradientBrush;
     Microsoft::WRL::ComPtr<ID2D1PathGeometry> mountain;
     Microsoft::WRL::ComPtr<ID2D1PathGeometry> sun;
     . . .
};


MountainView.cpp
. . .
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE , LPTSTR cmdLine, int cmdShow){
     MountainView app;
     app.CreateMainWindow(L"MountainView", cmdShow, IDI_MountainView, NULL, (HBRUSH)::GetStockObject(NULL_BRUSH), hInstance);
     return app.MessageLoop(IDC_MountainView);
}

void MountainView::Window_Open(Win::Event& e)
{
     HRESULT hr;
     Com::Exception ex;
     try
     {
          //___________________________________________________________________________________ 1. Create a 2DFactory
          hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, d2DFactory.GetAddressOf());
          ex.ok(L"D2D1CreateFactory", hr);
     }
     catch (Com::Exception& excep)
     {
          excep.Display(hWnd, L"MountainView");
     }
}

void MountainView::Window_Paint(Win::Event& e)
{
     // _______________________________________________________________________________ 1. Create device resources
     if (renderTarget == nullptr)
     {
          // _______________________________________________________________________________ 1. Create a render target
          D2D1_SIZE_U size = D2D1::SizeU(width, height);
          if (FAILED(d2DFactory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, size), &renderTarget))) return;
          // _______________________________________________________________________________ 2. Create a path geomtery for a Mountain
          mountain = nullptr; // Release previous resource
          if (FAILED(d2DFactory->CreatePathGeometry(&mountain))) return;
          //
          Microsoft::WRL::ComPtr<ID2D1GeometrySink> sink;
          if (SUCCEEDED(mountain->Open(&sink)))
          {
               sink->SetFillMode(D2D1_FILL_MODE_WINDING);
               sink->BeginFigure(D2D1::Point2F(550, 426),     D2D1_FIGURE_BEGIN_FILLED);
               D2D1_POINT_2F points[] ={D2D1::Point2F(362, 192), D2D1::Point2F(298, 262), D2D1::Point2F(266     , 218),
                    D2D1::Point2F(202     , 328), D2D1::Point2F(162     , 298), D2D1::Point2F(46, 426), D2D1::Point2F(550, 426)};
               sink->AddLines(points, ARRAYSIZE(points));
               sink->EndFigure(D2D1_FIGURE_END_CLOSED);
               sink->Close();
          }
          sink = nullptr;
          // _______________________________________________________________________________ 3. Create a path geomtery for the Sun
          sun = nullptr; // Release previous resource
          if (FAILED(d2DFactory->CreatePathGeometry(&sun))) return;
          if (SUCCEEDED(sun->Open(&sink)))
          {
               sink->SetFillMode(D2D1_FILL_MODE_WINDING);
               sink->BeginFigure(D2D1::Point2F(550, 426), D2D1_FIGURE_BEGIN_FILLED);
               sink->AddArc(D2D1::ArcSegment(
                    D2D1::Point2F(885, 426), // end point
                    D2D1::SizeF(170, 170),
                    0.0f, // rotation angle
                    D2D1_SWEEP_DIRECTION_CLOCKWISE,
                    D2D1_ARC_SIZE_SMALL
               ));
               sink->EndFigure(D2D1_FIGURE_END_CLOSED);
               //
               sink->BeginFigure(D2D1::Point2F(600, 332), D2D1_FIGURE_BEGIN_HOLLOW);
               sink->AddBezier(D2D1::BezierSegment(D2D1::Point2F(600, 332), D2D1::Point2F(594,326), D2D1::Point2F(585, 328)));
               sink->AddBezier(D2D1::BezierSegment(D2D1::Point2F(576, 329), D2D1::Point2F(572, 323), D2D1::Point2F(572, 323)));
               sink->EndFigure(D2D1_FIGURE_END_OPEN);
               //
               sink->Close();
          }
          sink = nullptr;
          //______________________________________________________________________________ 3. Create green brush
          greenBrush = nullptr; // Release previous resource
          if (FAILED(renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LawnGreen), &greenBrush))) return;
          //______________________________________________________________________________ 4. Create black brush
          blackBrush = nullptr; // Release previous resource
          if (FAILED(renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &blackBrush))) return;
          //______________________________________________________________________________ 5. Create gradiente brush
          gradientBrush = nullptr; // Release previous resource
          Microsoft::WRL::ComPtr<ID2D1GradientStopCollection> gradientStopColletion;
          D2D1_GRADIENT_STOP gradientStop[2];
          gradientStop[0].color = D2D1::ColorF(D2D1::ColorF::Yellow, 1);
          gradientStop[0].position = 0.0f;
          gradientStop[1].color = D2D1::ColorF(D2D1::ColorF::Orange, 1);
          gradientStop[1].position = 1.0f;
          if (FAILED(renderTarget->CreateGradientStopCollection(gradientStop, 2, D2D1_GAMMA_2_2,D2D1_EXTEND_MODE_CLAMP, &gradientStopColletion))) return;
          if (FAILED(renderTarget->CreateRadialGradientBrush(D2D1::RadialGradientBrushProperties(D2D1::Point2F(500, 426), D2D1::Point2F(0, 0), 500, 426),
               gradientStopColletion.Get(), &gradientBrush))) return;
     }
     //_______________________________________________________________________________ 6. BeginDraw
     renderTarget->BeginDraw();
     renderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
     renderTarget->Clear(D2D1::ColorF(D2D1::ColorF::LightCyan));
     //_______________________________________________________________________________ 7. Draw scene
     renderTarget->FillGeometry(mountain.Get(), greenBrush.Get());
     renderTarget->DrawGeometry(mountain.Get(), blackBrush.Get(), 2.0f);
     renderTarget->FillGeometry(sun.Get(), gradientBrush.Get());
     renderTarget->DrawGeometry(sun.Get(), blackBrush.Get(), 2.0f);
     //_______________________________________________________________________________ 8. EndDraw
     if (renderTarget->EndDraw()==D2DERR_RECREATE_TARGET) renderTarget = nullptr;
     ::ValidateRect(hWnd, NULL);
}

void MountainView::Window_Size(Win::Event& e)
{
     if (renderTarget != NULL) renderTarget->Resize(D2D1::SizeU(width, height));
}

void MountainView::Window_KeyDown(Win::Event& e)
{
     switch (e.wParam)
     {
     case VK_ESCAPE:
          ::DestroyWindow(hWnd);
          break;
     }
}



Problem 5
Create a Wintempla Window application called PictureView to draw an image using Direct2D (observe that this project is not a DirectX application). After creating the application, open Wintempla and double click the on the GUI editor to select the events: KeyDown, Paint and Size. Do not forget to edit the stdafx.file to include Direct2D and DirectWrite libraries. For this exercise, you need an uncompressed 24 bits (or 32 bits) bitmap. You can also use a GIF.
Cree una aplicación de ventana de Wintempla llamada PictureView para dibujar una imagen usando Direct2D (observe que este proyecto no es una aplicación de DirectX). Después de crear la aplicación, abra Wintempla y haga clic doble en el editor de la GUI para seleccionar los eventos: KeyDown, Paint y Size. No se olvide de editar el archivo stdafx.h para incluir las librerías de Direct2D y DirectWrite. Para este ejercicio, usted necesita un bitmap sin compresión de 24 o 32 bits. Usted también puede usar un GIF.

PictureViewRun

PictureView.h
#pragma once //______________________________________ PictureView.h
#include "Resource.h"
class PictureView: public Win::Window
{
public:
     PictureView()
     {
          ::CoInitialize(NULL);
     }
     ~PictureView()
     {
          ::CoUninitialize();
     }
     CG::DIBitmap diBitmap;
     Microsoft::WRL::ComPtr<ID2D1Factory> d2DFactory;
     Microsoft::WRL::ComPtr<ID2D1HwndRenderTarget> renderTarget;
     Microsoft::WRL::ComPtr<ID2D1Bitmap> bitmap;
     . . .
};


PictureView.cpp
. . .
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE , LPTSTR cmdLine, int cmdShow){
     PictureView app;
     app.CreateMainWindow(L"PictureView", cmdShow, IDI_PictureView, NULL, (HBRUSH)::GetStockObject(NULL_BRUSH), hInstance);
     return app.MessageLoop(IDC_PictureView);
}

void PictureView::Window_Open(Win::Event& e)
{
     HRESULT hr;
     Com::Exception ex;
     try
     {
          //___________________________________________________________________________________ 1. Create a 2DFactory
          hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, d2DFactory.GetAddressOf());
          ex.ok(L"D2D1CreateFactory", hr);
     }
     catch (Com::Exception& excep)
     {
          excep.Display(hWnd, L"PictureView");
     }
     const wchar_t* error = diBitmap.Load(L"pascal.gif");
     if (error != nullptr)
     {
          this->MessageBox(error, L"PictureView", MB_OK | MB_ICONERROR);
     }
}

void PictureView::Window_Paint(Win::Event& e)
{
     // _______________________________________________________________________________ 1. Create device resources
     if (renderTarget == nullptr)
     {
          // __________________________________________________ 1.1. Create a render target
          D2D1_SIZE_U size = D2D1::SizeU(width, height);
          if (FAILED(d2DFactory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, size), &renderTarget))) return;
          //__________________________________________________ 1.2. Create a bitmap
          bitmap = nullptr; // Release previous resource
          size.width = diBitmap.GetWidth();
          size.height = diBitmap.GetHeight();
          D2D1_BITMAP_PROPERTIES bitmapProperties;
          bitmapProperties.dpiX = 96.0f;
          bitmapProperties.dpiY = 96.0f;
          bitmapProperties.pixelFormat.format = DXGI_FORMAT_R8G8B8A8_UNORM;
          bitmapProperties.pixelFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;
          const size_t count = diBitmap.GetWidth()*diBitmap.GetHeight();
           CG::Color* pixels = new CG::Color[count];
           diBitmap.CopyPixels(pixels);
          HRESULT hr = renderTarget->CreateBitmap(size, pixels, 4*diBitmap.GetWidth(), &bitmapProperties, bitmap.GetAddressOf());
          delete[] pixels;
          if (FAILED(hr)) return;
     }
     //_______________________________________________________________________________ 2. BeginDraw
     renderTarget->BeginDraw();
     renderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
     renderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
     //_______________________________________________________________________________ 3. Draw bitmap
     D2D_RECT_F rect = {0.0f, 100.0f, (float)diBitmap.GetWidth(), (float)(100+diBitmap.GetHeight())};
     renderTarget->DrawBitmap(bitmap.Get(), rect);

     //_______________________________________________________________________________ 4. EndDraw
     if (renderTarget->EndDraw()==D2DERR_RECREATE_TARGET) renderTarget = nullptr;
     ::ValidateRect(hWnd, NULL);
}

void PictureView::Window_Size(Win::Event& e)
{
     if (renderTarget != NULL) renderTarget->Resize(D2D1::SizeU(width, height));
}



© Copyright 2000-2019 Wintempla selo. All Rights Reserved. Sep 05 2019. Home