The Brush Origin

Godot引擎原生纹理绘制器开发指南:从原理到实现 纹理贴图是游戏开发中定义物体表面视觉属性的核心技术,它通过像素信息控制颜色、法线、粗糙度等材质表现。其原理是将二维图像通过UV坐标映射到三维模型表面,实现细节与真实感。在游戏引擎中,纹理系统直接影响渲染效率与美术效果,是资源管线的重要环节。对于独立开发与快速迭代,直接在引擎内编辑纹理能极大提升工作流效率,避免频繁切换外部软件。本文聚焦Godot引擎,探讨如何构建一个原生集成的非破坏性纹理绘制系统,支持图层混合与GPU加速绘制,解决'godot双瓦片系统'地形绘制与'godot导出apk'前的纹理优化等实际开 阅读详情
 

The Brush Origin

One attribute of a device context that you should be aware of when using dithered brush colors or hatch brushes is the brush origin. When Windows fills an area with a hatched or dithered brush pattern, it tiles an 8-pixel by 8-pixel pattern horizontally and vertically within the affected area. By default, the origin for this pattern, better known as the brush origin, is the device point (0,0)—the screen pixel in the upper left corner of the window. This means that a pattern drawn in a rectangle that begins 100 pixels to the right of and below the origin will be aligned somewhat differently with respect to the rectangle's border than a pattern drawn in a rectangle positioned a few pixels to the left or right, as shown in Figure 2-8. In many applications, it doesn't matter; the user isn't likely to notice minute differences in brush alignment. However, in some situations it matters a great deal.

Click to view at full size.

Figure 2-8. Brush alignment.

Suppose you're using a hatch brush to fill a rectangle and you're animating the motion of that rectangle by repeatedly erasing it and redrawing it 1 pixel to the right or the left. If you don't reset the brush origin to a point that stays in the same position relative to the rectangle before each redraw, the hatch pattern will "walk" as the rectangle moves.

The solution? Before selecting the brush into the device context and drawing the rectangle, call CGdiObject::UnrealizeObject on the brush object to permit the brush origin to be moved. Then call CDC::SetBrushOrg to align the brush origin with the rectangle's upper left corner, as shown here:

CPoint point (x1, y1);
dc.LPtoDP (&point);
point.x %= 8;
point.y %= 8;
brush.UnrealizeObject ();
dc.SetBrushOrg (point);
dc.SelectObject (&brush);
dc.Rectangle (x1, y1, x2, y2);

In this example, point is a CPoint object that holds the logical coordinates of the rectangle's upper left corner. LPtoDP is called to convert logical coordinates into device coordinates (brush origins are always specified in device coordinates), and a modulo-8 operation is performed on the resulting values because coordinates passed to SetBrushOrg should fall within the range 0 through 7. Now the hatch pattern will be aligned consistently no matter where in the window the rectangle is drawn.

Drawing Text

You've already seen one way to output text to a window. The CDC::DrawText function writes a string of text to a display surface. You tell DrawText where to draw its output by specifying both a formatting rectangle and a series of option flags indicating how the text is to be positioned within the rectangle. In Chapter 1's Hello program, the statement

dc.DrawText (_T ("Hello, MFC"), -1, &rect,
    DT_SINGLELINE ¦ DT_CENTER ¦ DT_VCENTER);

drew "Hello, MFC" so that it was centered in the window. rect was a rectangle object initialized with the coordinates of the window's client area, and the DT_CENTER and DT_VCENTER flags told DrawText to center its output in the rectangle both horizontally and vertically.

DrawText is one of several text-related functions that are members of MFC's CDC class. Some of the others are listed in the table below. One of the most useful is TextOut, which outputs text like DrawText but accepts an x-y coordinate pair that specifies where the text will be output and also uses the current position if it is asked to. The statement

dc.TextOut (0, 0, CString (_T ("Hello, MFC")));

writes "Hello, MFC" to the upper left of the display surface represented by dc. A related function named TabbedTextOut works just like TextOut except that it expands tab characters into white space. (If a string passed to TextOut contains tabs, the characters show up as rectangles in most fonts.) Tab positions are specified in the call to TabbedTextOut. A related function named ExtTextOut gives you the added option of filling a rectangle surrounding the output text with an opaque background color. It also gives the programmer precise control over intercharacter spacing.

By default, the coordinates passed to TextOut, TabbedTextOut, and ExtTextOut specify the location of the upper left corner of the text's leftmost character cell. However, the relationship between the coordinates passed to TextOut and the characters in the output string, a property known as the text alignment, is an attribute of the device context. You can change it with CDC::SetTextAlign. For example, after a

dc.SetTextAlign (TA_RIGHT);

statement is executed, the x coordinate passed to TextOut specifies the rightmost position in the character cell—perfect for drawing right-aligned text.

You can also call SetTextAlign with a TA_UPDATECP flag to instruct TextOut to ignore the x and y arguments passed to it and use the device context's current position instead. When the text alignment includes TA_UPDATECP, TextOut updates the x component of the current position each time a string is output. One use for this feature is to achieve proper spacing between two or more character strings that are output on the same line.

CDC Text Functions

FunctionDescription
DrawText Draws text in a formatting rectangle
TextOut Outputs a line of text at the current or specified position
TabbedTextOut Outputs a line of text that includes tabs
ExtTextOut Outputs a line of text and optionally fills a rectangle with a background color or varies the intercharacter spacing
GetTextExtent Computes the width of a string in the current font
GetTabbedTextExtentComputes the width of a string with tabs in the current font
GetTextMetrics Returns font metrics (character height, average character width, and so on) for the current font
SetTextAlign Sets alignment parameters for TextOut and other output functions
SetTextJustificationSpecifies the added width that is needed to justify a string of text
SetTextColorSets the device context's text output color
SetBkColorSets the device context's background color, which determines the fill color used behind characters that are output to a display surface

Two functions—GetTextMetrics and GetTextExtent—let you retrieve information about the font that is currently selected into the device context. GetTextMetrics fills a TEXTMETRIC structure with information on the characters that make up the font. GetTextExtent returns the width of a given string, in logical units, rendered in that font. (Use GetTabbedTextExtent if the string contains tab characters.) One use for GetTextExtent is to gauge the width of a string prior to outputting it in order to compute how much space is needed between words to fully justify the text. If nWidth is the distance between left and right margins, the following code outputs the text "Now is the time" and justifies the output to both margins:

CString string = _T ("Now is the time");
CSize size = dc.GetTextExtent (string);
dc.SetTextJustification (nWidth - size.cx, 3);
dc.TextOut (0, y, string);

The second parameter passed to SetTextJustification specifies the number of break characters in the string. The default break character is the space character. After SetTextJustification is called, subsequent calls to TextOut and related text output functions distribute the space specified in the SetTextJustification's first parameter evenly between all the break characters.

GDI Fonts and the CFont Class

All CDC text functions use the font that is currently selected into the device context. A font is a group of characters of a particular size (height) and typeface that share common attributes such as character weight—for example, normal or boldface. In classical typography, font sizes are measured in units called points. One point equals about 1/72 inch. Each character in a 12-point font is nominally 1/6 inch tall, but in Windows, the actual height can vary somewhat depending on the physical characteristics of the output device. The term typeface describes a font's basic style. Times New Roman is one example of a typeface; Courier New is another.

A font is a GDI object, just as a pen or a brush is. In MFC, fonts are represented by objects of the CFont class. Once a CFont object is constructed, you create the underlying GDI font by calling the CFont object's CreateFont, CreateFontIndirect, CreatePointFont, or CreatePointFontIndirect function. Use CreateFont or CreateFontIndirect if you want to specify the font size in pixels, and use CreatePointFont and CreatePointFontIndirect to specify the font size in points. Creating a 12-point Times New Roman screen font with CreatePointFont requires just two lines of code:

CFont font;
font.CreatePointFont (120, _T ("Times New Roman"));

Doing the same with CreateFont requires you to query the device context for the logical number of pixels per inch in the vertical direction and to convert points to pixels:

CClientDC dc (this);
int nHeight = -((dc.GetDeviceCaps (LOGPIXELSY) * 12) / 72);
CFont font;
font.CreateFont (nHeight, 0, 0, 0, FW_NORMAL, 0, 0, 0,
    DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS,
    DEFAULT_QUALITY, DEFAULT_PITCH ¦ FF_DONTCARE,
    _T ("Times New Roman"));

Incidentally, the numeric value passed to CreatePointFont is the desired point size times 10. This allows you to control the font size down to 1/10 point—plenty accurate enough for most applications, considering the relatively low resolution of most screens and other commonly used output devices.

The many parameters passed to CreateFont specify, among other things, the font weight and whether characters in the font are italicized. You can't create a bold, italic font with CreatePointFont, but you can with CreatePointFontIndirect. The following code creates a 12-point bold, italic Times New Roman font using CreatePointFontIndirect.

LOGFONT lf;
::ZeroMemory (&lf, sizeof (lf));
lf.lfHeight = 120;
lf.lfWeight = FW_BOLD;
lf.lfItalic = TRUE;
::lstrcpy (lf.lfFaceName, _T ("Times New Roman"));

CFont font;
font.CreatePointFontIndirect (&lf);

LOGFONT is a structure whose fields define all the characteristics of a font. ::ZeroMemory is an API function that zeroes a block of memory, and ::lstrcpy is an API function that copies a text string from one memory location to another. You can use the C run time's memset and strcpy functions instead (actually, you should use _tcscpy in lieu of strcpy so the call will work with ANSI or Unicode characters), but using Windows API functions frequently makes an executable smaller by reducing the amount of statically linked code.

After creating a font, you can select it into a device context and draw with it using DrawText, TextOut, and other CDC text functions. The following OnPaint handler draws "Hello, MFC" in the center of a window. But this time the text is drawn using a 72-point Arial typeface, complete with drop shadows. (See Figure 2-9.)

void CMainWindow::OnPaint ()
{
    CRect rect;
    GetClientRect (&rect);

    CFont font;
    font.CreatePointFont (720, _T ("Arial"));

    CPaintDC dc (this);
    dc.SelectObject (&font);
    dc.SetBkMode (TRANSPARENT);

    CString string = _T ("Hello, MFC");

    rect.OffsetRect (16, 16);
    dc.SetTextColor (RGB (192, 192, 192));
    dc.DrawText (string, &rect, DT_SINGLELINE ¦
        DT_CENTER ¦ DT_VCENTER);

    rect.OffsetRect (-16, -16);
    dc.SetTextColor (RGB (0, 0, 0));
    dc.DrawText (string, &rect, DT_SINGLELINE ¦
        DT_CENTER ¦ DT_VCENTER);
}

Click to view at full size.

Figure 2-9. "Hello, MFC" rendered in 72-point Arial with drop shadows.

The shadow effect is achieved by drawing the text string twice—once a few pixels to the right of and below the center of the window, and once in the center. MFC's CRect::OffsetRect function makes it a snap to "move" rectangles by offsetting them a specified distance in the x and y directions.

What happens if you try to create, say, a Times New Roman font on a system that doesn't have Times New Roman installed? Rather than fail the call, the GDI will pick a similar typeface that is installed. An internal font-mapping algorithm is called to pick the best match, and the results aren't always what one might expect. But at least your application won't output text just fine on one system and mysteriously output nothing on another.

Raster Fonts vs. TrueType Fonts

Most GDI fonts fall into one of two categories: raster fonts and TrueType fonts. Raster fonts are stored as bitmaps and look best when they're displayed in their native sizes. One of the most useful raster fonts provided with Windows is MS Sans Serif, which is commonly used (in its 8-point size) on push buttons, radio buttons, and other dialog box controls. Windows can scale raster fonts by duplicating rows and columns of pixels, but the results are rarely pleasing to the eye due to stair-stepping effects.

The best fonts are TrueType fonts because they scale well to virtually any size. Like PostScript fonts, TrueType fonts store character outlines as mathematical formulas. They also include "hint" information that's used by the GDI's TrueType font rasterizer to enhance scalability. You can pretty much bank on the fact that any system your application runs on will have the following TrueType fonts installed, because all four are provided with Windows:

  • Times New Roman

  • Arial

  • Courier New

  • Symbol

In Chapter 7, you'll learn how to query the system for font information and how to enumerate the fonts that are installed. Such information can be useful if your application requires precise character output or if you want to present a list of installed fonts to the user.

Rotated Text

One question that's frequently asked about GDI text output is "How do I display rotated text?" There are two ways to do it, one of which works only in Microsoft Windows NT and Windows 2000. The other method is compatible with all 32-bit versions of Windows, so it's the one I'll describe here.

The secret is to create a font with CFont::CreateFontIndirect or CFont::CreatePointFontIndirect and to specify the desired rotation angle (in degrees) times 10 in the LOGFONT structure's lfEscapement and lfOrientation fields. Then you output the text in the normal manner—for example, using CDC::TextOut. Conventional text has an escapement and orientation of 0; that is, it has no slant and is drawn on a horizontal. Setting these values to 450 rotates the text counterclockwise 45 degrees. The following OnPaint handler increments lfEscapement and lfOrientation in units of 15 degrees and uses the resulting fonts to draw the radial text array shown in Figure 2-10:

void CMainWindow::OnPaint ()
{
    CRect rect;
    GetClientRect (&rect);

    CPaintDC dc (this);
    dc.SetViewportOrg (rect.Width () / 2, rect.Height () / 2);
    dc.SetBkMode (TRANSPARENT);

    for (int i=0; i<3600; i+=150) {
        LOGFONT lf;
        ::ZeroMemory (&lf, sizeof (lf));
        lf.lfHeight = 160;
        lf.lfWeight = FW_BOLD;
        lf.lfEscapement = i;
        lf.lfOrientation = i;
        ::lstrcpy (lf.lfFaceName, _T ("Arial"));

        CFont font;
        font.CreatePointFontIndirect (&lf);

        CFont* pOldFont = dc.SelectObject (&font);
        dc.TextOut (0, 0, CString (_T ("          Hello, MFC")));
        dc.SelectObject (pOldFont);
    }
}

This technique works great with TrueType fonts, but it doesn't work at all with raster fonts.

Click to view at full size.

Figure 2-10. Rotated text.

Stock Objects

Windows predefines a handful of pens, brushes, fonts, and other GDI objects that can be used without being explicitly created. Called stock objects, these GDI objects can be selected into a device context with the CDC::SelectStockObject function or assigned to an existing CPen, CBrush, or other object with CGdiObject::CreateStockObject. CGdiObject is the base class for CPen, CBrush, CFont, and other MFC classes that represent GDI objects.

The following table shows a partial list of the available stock objects. Stock pens go by the names WHITE_PEN, BLACK_PEN, and NULL_PEN. WHITE_PEN and BLACK_PEN draw solid lines that are 1 pixel wide. NULL_PEN draws nothing. The stock brushes include one white brush, one black brush, and three shades of gray. HOLLOW_BRUSH and NULL_BRUSH are two different ways of referring to the same thing—a brush that paints nothing. SYSTEM_FONT is the font that's selected into every device context by default.

Commonly Used Stock Objects

ObjectDescription
NULL_PENPen that draws nothing
BLACK_PENBlack pen that draws solid lines 1 pixel wide
WHITE_PENWhite pen that draws solid lines 1 pixel wide
NULL_BRUSHBrush that draws nothing
HOLLOW_BRUSHBrush that draws nothing (same as NULL_BRUSH)
BLACK_BRUSHBlack brush
DKGRAY_BRUSHDark gray brush
GRAY_BRUSHMedium gray brush
LTGRAY_BRUSH Light gray brush
WHITE_BRUSH White brush
ANSI_FIXED_FONT Fixed-pitch ANSI font
ANSI_VAR_FONTVariable-pitch ANSI font
SYSTEM_FONTVariable-pitch system font
SYSTEM_FIXED_FONTFixed-pitch system font

Suppose you want to draw a light gray circle with no border. How do you do it? Here's one way:

CPen pen (PS_NULL, 0, (RGB (0, 0, 0)));
dc.SelectObject (&pen);
CBrush brush (RGB (192, 192, 192));
dc.SelectObject (&brush);
dc.Ellipse (0, 0, 100, 100);

But since NULL pens and light gray brushes are stock objects, here's a better way:

dc.SelectStockObject (NULL_PEN);
dc.SelectStockObject (LTGRAY_BRUSH);
dc.Ellipse (0, 0, 100, 100);

The following code demonstrates a third way to draw the circle. This time the stock objects are assigned to a CPen and a CBrush rather than selected into the device context directly:

CPen pen;
pen.CreateStockObject (NULL_PEN);
dc.SelectObject (&pen);

CBrush brush;
brush.CreateStockObject (LTGRAY_BRUSH);
dc.SelectObject (&brush);

dc.Ellipse (0, 0, 100, 100);

Which of the three methods you use is up to you. The second method is the shortest, and it's the only one that's guaranteed not to throw an exception since it doesn't create any GDI objects.

Deleting GDI Objects

Pens, brushes, and other objects created from CGdiObject-derived classes are resources that consume space in memory, so it's important to delete them when you no longer need them. If you create a CPen, CBrush, CFont, or other CGdiObject on the stack, the associated GDI object is automatically deleted when CGdiObject goes out of scope. If you create a CGdiObject on the heap with new, be sure to delete it at some point so that its destructor will be called. The GDI object associated with a CGdiObject can be explicitly deleted by calling CGdiObject::DeleteObject. You never need to delete stock objects, even if they are "created" with CreateStockObject.

In 16-bit Windows, GDI objects frequently contributed to the problem of resource leakage, in which the Free System Resources figure reported by Program Manager gradually decreased as applications were started and terminated because some programs failed to delete the GDI objects they created. All 32-bit versions of Windows track the resources a program allocates and deletes them when the program ends. However, it's still important to delete GDI objects when they're no longer needed so that the GDI doesn't run out of memory while a program is running. Imagine an OnPaint handler that creates 10 pens and brushes every time it's called but neglects to delete them. Over time, OnPaint might create thousands of GDI objects that occupy space in system memory owned by the Windows GDI. Pretty soon, calls to create pens and brushes will fail, and the application's OnPaint handler will mysteriously stop working.

In Visual C++, there's an easy way to tell whether you're failing to delete pens, brushes, and other resources: Simply run a debug build of your application in debugging mode. When the application terminates, resources that weren't freed will be listed in the debugging window. MFC tracks memory allocations for CPen, CBrush, and other CObject-derived classes so that it can notify you when an object hasn't been deleted. If you have difficulty ascertaining from the debug messages which objects weren't deleted, add the statement

#define new DEBUG_NEW

to your application's source code files after the statement that includes Afxwin.h. (In AppWizard-generated applications, this statement is included automatically.) Debug messages for unfreed objects will then include line numbers and file names to help you pinpoint leaks.

Deselecting GDI Objects

It's important to delete the GDI objects you create, but it's equally important to never delete a GDI object while it's selected into a device context. Code that attempts to paint with a deleted object is buggy code. The only reason it doesn't crash is that the Windows GDI is sprinkled with error-checking code to prevent such crashes from occurring.

Abiding by this rule isn't as easy as it sounds. The following OnPaint handler allows a brush to be deleted while it's selected into a device context. Can you figure out why?

void CMainWindow::OnPaint ()
{
    CPaintDC dc (this);
    CBrush brush (RGB (255, 0, 0));
    dc.SelectObject (&brush);
    dc.Ellipse (0, 0, 200, 100);
}

Here's the problem. A CPaintDC object and a CBrush object are created on the stack. Since the CBrush is created second, its destructor gets called first. Consequently, the associated GDI brush is deleted before dc goes out of scope. You could fix this by creating the brush first and the DC second, but code whose robustness relies on stack variables being created in a particular order is bad code indeed. As far as maintainability goes, it's a nightmare.

The solution is to select the CBrush out of the device context before the CPaintDC object goes out of scope. There is no UnselectObject function, but you can select an object out of a device context by selecting in another object. Most Windows programmers make it a practice to save the pointer returned by the first call to SelectObject for each object type and then use that pointer to reselect the default object. An equally viable approach is to select stock objects into the device context to replace the objects that are currently selected in. The first of these two methods is illustrated by the following code:

CPen pen (PS_SOLID, 1, RGB (255, 0, 0));
CPen* pOldPen = dc.SelectObject (&pen);
CBrush brush (RGB (0, 0, 255));
CBrush* pOldBrush = dc.SelectObject (&brush);
  
dc.SelectObject (pOldPen);
dc.SelectObject (pOldBrush);

The second method works like this:

CPen pen (PS_SOLID, 1, RGB (255, 0, 0));
dc.SelectObject (&pen);
CBrush brush (RGB (0, 0, 255));
dc.SelectObject (&brush); 
  
dc.SelectStockObject (BLACK_PEN);
dc.SelectStockObject (WHITE_BRUSH);

The big question is why this is necessary. The simple truth is that it's not. In modern versions of Windows, there's no harm in allowing a GDI object to be deleted a split second before a device context is released, especially if you're absolutely sure that no drawing will be done in the interim. Still, cleaning up a device context by deselecting the GDI objects you selected in is a common practice in Windows programming. It's also considered good form, so it's something I'll do throughout this book.

Incidentally, GDI objects are occasionally created on the heap, like this:

CPen* pPen = new CPen (PS_SOLID, 1, RGB (255, 0, 0));
CPen* pOldPen = dc.SelectObject (pPen);

At some point, the pen must be selected out of the device context and deleted. The code to do it might look like this:

dc.SelectObject (pOldPen);
delete pPen;

Since the SelectObject function returns a pointer to the object selected out of the device context, it might be tempting to try to deselect the pen and delete it in one step:

delete dc.SelectObject (pOldPen);

But don't do this. It works fine with pens, but it might not work with brushes. Why? Because if you create two identical CBrushes, 32-bit Windows conserves memory by creating just one GDI brush and you'll wind up with two CBrush pointers that reference the same HBRUSH. (An HBRUSH is a handle that uniquely identifies a GDI brush, just as an HWND identifies a window and an HDC identifies a device context. A CBrush wraps an HBRUSH and stores the HBRUSH handle in its m_hObject data member.) Because CDC::SelectObject uses an internal table maintained by MFC to convert the HBRUSH handle returned by SelectObject to a CBrush pointer and because that table assumes a one-to-one mapping between HBRUSHes and CBrushes, the CBrush pointer you get back might not match the CBrush pointer returned by new. Be sure you pass delete the pointer returned by new. Then both the GDI object and the C++ object will be properly destroyed.

The Ruler Application

The best way to get acquainted with the GDI and the MFC classes that encapsulate it is to write code. Let's start with a very simple application. Figure 2-12 contains the source code for Ruler, a program that draws a 12-inch ruler on the screen. Ruler's output is shown in Figure 2-11.

Click to view at full size.

Figure 2-11. The Ruler window.

Figure 2-12. The Ruler application.

Ruler.h

class CMyApp : public CWinApp
{
public:
    virtual BOOL InitInstance ();
};

class CMainWindow : public CFrameWnd
{
public:
    CMainWindow ();

protected:
    afx_msg void OnPaint ();
    DECLARE_MESSAGE_MAP ()
};

Ruler.cpp

#include <afxwin.h>
#include "Ruler.h"

CMyApp myApp;

/////////////////////////////////////////////////////////////////////////
// CMyApp member functions

BOOL CMyApp::InitInstance ()
{
    m_pMainWnd = new CMainWindow;
    m_pMainWnd->ShowWindow (m_nCmdShow);
    m_pMainWnd->UpdateWindow ();
    return TRUE;
}

/////////////////////////////////////////////////////////////////////////
// CMainWindow message map and member functions

BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
    ON_WM_PAINT ()
END_MESSAGE_MAP ()

CMainWindow::CMainWindow ()
{
    Create (NULL, _T ("Ruler"));
}

void CMainWindow::OnPaint ()
{
    CPaintDC dc (this);
    
    //
    // Initialize the device context.
    //
    dc.SetMapMode (MM_LOENGLISH);
    dc.SetTextAlign (TA_CENTER ¦ TA_BOTTOM);
    dc.SetBkMode (TRANSPARENT);

    //
    // Draw the body of the ruler.
    //

    CBrush brush (RGB (255, 255, 0));
    CBrush* pOldBrush = dc.SelectObject (&brush);
    dc.Rectangle (100, -100, 1300, -200);
    dc.SelectObject (pOldBrush);

    //
    // Draw the tick marks and labels.
    //
    for (int i=125; i<1300; i+=25) {
        dc.MoveTo (i, -192);
        dc.LineTo (i, -200);
    }

    for (i=150; i<1300; i+=50) {
        dc.MoveTo (i, -184);
        dc.LineTo (i, -200);
    }

    for (i=200; i<1300; i+=100) {
        dc.MoveTo (i, -175);
        dc.LineTo (i, -200);

        CString string;
        string.Format (_T ("%d"), (i / 100) - 1);
        dc.TextOut (i, -175, string);
    }

}

The structure of Ruler is similar to that of the Hello application presented in Chapter 1. The CMyApp class represents the application itself. CMyApp::InitInstance creates a frame window by constructing a CMainWindow object, and CMainWindow's constructor calls Create to create the window you see on the screen. CMainWindow::OnPaint handles all the drawing. The body of the ruler is drawn with CDC::Rectangle, and the hash marks are drawn with CDC::LineTo and CDC::MoveTo. Before the rectangle is drawn, a yellow brush is selected into the device context so that the body of the ruler will be painted yellow. Numeric labels are drawn with CDC::TextOut and positioned over the tick marks by calling SetTextAlign with TA_CENTER and TA_BOTTOM flags and passing TextOut the coordinates of the top of each tick mark. Before TextOut is called for the first time, the device context's background mode is set to TRANSPARENT. Otherwise, the numbers on the face of the ruler would be drawn with white backgrounds.

Rather than hardcode the strings passed to TextOut, Ruler uses CString::Format to generate text on the fly. CString is the MFC class that represents text strings. CString::Format works like C's printf function, converting numeric values to text and substituting them for placeholders in a formatting string. Windows programmers who work in C frequently use the ::wsprintf API function for text formatting. Format does the same thing for CString objects without requiring an external function call. And unlike ::wsprintf, Format supports the full range of printf formatting codes, including codes for floating-point and string variable types.

Ruler uses the MM_LOENGLISH mapping mode to scale its output so that 1 inch on the ruler corresponds to 1 logical inch on the screen. Hold a real ruler up to the screen and on most PCs you'll find that 1 logical inch equals a little more than 1 physical inch. If the ruler is output to a printer instead, logical inches and physical inches will match exactly.

Godot地形纹理混合画笔工具开发:从原理到实战实现 在3D游戏开发中,纹理混合是实现自然地形效果的核心技术,它通过权重控制下的线性插值,将多张纹理无缝融合,从而消除生硬的视觉边界,提升场景沉浸感。这项技术的关键在于高效存储与动态修改混合权重数据,通常利用顶点颜色或自定义纹理通道实现。其技术价值在于将专业级美术控制能力集成到实时编辑工作流中,极大提升了地形编辑的迭代效率和艺术表现力。在应用场景上,它广泛适用于开放世界、RPG、模拟经营等需要自然地貌的3D项目。本文将以Godot引擎为例,深入解析如何开发一个基于画笔工具的地形纹理混合系统,涵盖着色器编程、编辑器 阅读详情

相关推荐

Palantir Vertex:数字孪生模拟与决策系统深度指南

Palantir Vertex是Foundry系统中的核心数字孪生模块,本质上是一个决策模拟器而非简单的数据可视化工具。它基于本体层构建,通过对象关系网络模拟现实世界实体,填补数据模型与业务决策间的鸿沟。核心功能包括:创建隔离的沙盒场景进行假设测试、修改参数模拟不同干预方案、对比虚实数据发现异常,并最终将最优决策回传至业务系统。典型应用场景涵盖供应链韧性评估、资产维护优化和应急方案制定等,帮助用户在复杂环境中做出更优决策。

轩哥的个人研究和成长记录 899

QPainter绘图

QPainter 提供了高度优化的功能来完成大多数绘图 GUI 程序所需的工作。它可以绘制从简单的线条到复杂的形状(如馅饼和弦)的所有内容。它还可以绘制对齐的文本和像素图。通常,它在“自然”坐标系中绘制,但它也可以进行视图和世界变换。QPainter 可以对任何继承QPaintDevice类的对象进行操作。

xiaobai_cpp的博客 1858

头歌平台-人工智能导论实验(人脸识别)

答案仅供参考,自己动手丰衣足食!!!

qq_52119136的博客 3048

137-QPainter和Graphics/View绘图-QPainter绘图-填充

用QPainter 绘图时如果所绘制的图形是封闭的,且为QPainter设置了画刷,则系统自动在封闭的图形内填充画刷的图案,封闭的图形包括绘图路径、矩形、椭圆、多边形。除此之外,还可以为指定的矩形范围填充图案,此时不需要有封闭的边界线QPainter的方法中用于填充的方法如表所示主要方法介绍如下。下面的程序绘制文字,用渐变色分别显示文字和背景色,并用定时器实现动态移动画刷的起始点,产生动画效果。

***** 844

airodump-ng、aircrack-ng使用教程

wifi破解、airodump-ng、aircrack-ng脚本

ssmbyss的博客 2248

【实战】S7-PLCSIM Advanced V3.0 授权问题排查指南(Error Code:-30与LicenseNotFound深度解析)

本文深度解析S7-PLCSIM Advanced V3.0启动时遇到的Error Code:-30与LicenseNotFound报错问题。文章提供了一套系统性的排查指南,从检查WinPcap驱动兼容性、确保Automation License Manager服务运行,到正确安装浮动授权以及清理系统残留缓存,逐步解决授权链条中的各个环节故障,帮助用户彻底解决仿真环境启动失败的问题。

weixin_29185167的博客 733

【qt】填充

【代码】【qt】坐标转换。

lsz441的博客 1300

局放起始电压(PDIV)与击穿电压(BDV):绝缘系统设计的核心参数 [特殊字符]

在电力设备绝缘系统设计中,**局放起始电压(Partial Discharge Inception Voltage, PDIV)和击穿电压(Breakdown Voltage, BDV)**是两个至关重要的参数。它们直接反映了绝缘材料的性能和绝缘系统的可靠性,对变压器的设计、制造和运行具有重要指导意义。本文将深入探讨这两项参数的定义、测试方法及其与绝缘设计制造的关系,帮助读者全面理解其在电力设备中的核心作用。

mubiao05的博客 2654

Qpainter详解

QT绘图

weixin_53090658的博客 2325

投入产出表之直接消耗系数和完全消耗系数计算--基于Excel

介绍 上篇博客已介绍投入产出表的结构类型及意义解读,在此就不重复写了。 投入产出法中相对稳定的因素是一些系数,根据投入产出表可以计算很多系数: 案例 案例数据即流量矩阵,采用的是中国2012年的部分行业数据,若有不对,请批评指正哈。 直接消耗系数的计算 根据上表和直接消耗系数的计算公式,直接消耗系数矩阵通常用A表示。农林牧渔产品和服务部门对其他部门产品的直接消耗系数分别为: 这些消耗系数的经济意义是,农、林、牧、渔产品和服务部门每生产单位(1亿元)总产出,要直接消耗0.1378亿元本部门产品,0.26

m0_46271335的博客 7万+

基于STM32设计的自动追光系统(项目资料ID:2)

基于STM32设计的自动追光系统主要由光敏采集电路、单片机核心板电路和步进电机控制电路构成。通过光敏电阻采集环境光强信息,经 STM32 单片机处理后,控制步进电机转动,实现对光源的自动追踪。该系统具有响应速度快、追踪精度较高等优点,可应用于太阳能发电、智能照明等领域,为相关场景提供高效的光资源利用方案。

以培养嵌入式工程师为己任 1万+

Qt模块学习——绘图(I)

QPainter 提供高度优化的函数来完成 GUI 程序所需的大部分绘图操作。它可以绘制从简单线条到复杂形状(如饼图和和弦)的所有内容。它还可以绘制对齐的文本和像素图。通常,它会在“自然”坐标系中绘制,但也可以进行视图和世界变换。QPainter 可以对继承 QPaintDevice 类的任何对象进行操作。QPainter 的常见用途是在小部件的绘制事件中:构造和自定义(例如设置笔或画笔)绘制器。然后绘制。请记住在绘制后销毁 QPainter 对象。

charlie114514191的博客 1506

五种雷达波束模式简介及其应用场景

方位角和仰角都很窄的光束(像铅笔一样细);用于三维雷达,如仪表雷达、天气雷达和防空雷达。

珞瑜的博客 3585

The Brush Origin (转)

The Brush Origin (转)[@more@] The Brush Origin One attribute of a device context that you should be aware of wh...

csd3176的博客 272

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

FuncGodot地图编辑器集成:TrenchBroom GameConfig导出与Brush/Face Tag实战

FuncGodot 是一款 Godot 4 插件,能把 Quake `.map` 地图文件直接转换成带网格、材质和碰撞的 Godot 场景。本文带你实战它最核心的编辑器集成能力:一键导出 TrenchBroom GameConfig,并配置 Brush Tag 与 Face Tag,让你的地图编辑体验瞬间专业化。 ## 为什么要把 FuncGodot 接入 TrenchBroom 用 [Tre

gitblog_00324的博客 444

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

git将一个分支完全覆盖另外一个分支如:stable分支代码完全覆盖brush分支

当前分支是maser分支,我想将stable分支上的代码完全覆盖brush分支,首先切换到brush分支。 git reset --hard origin/stable执行上面的命令后brush分支上的代码就完全被stable分支上的代码覆盖了(本地分支),然后将本地分支强行推到远程分支。 git push -f 转载于:https://www.cnblogs.com/wangshuazi/...

weixin_34023863的博客 579

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

qradiant

我实在没有什么时间来整理好这个了,这一篇没有任何的技术含量,其实就是一些代码的描述罢了, 加之个人能力有限,理解不到家,有空再写清楚 关卡编辑器部分    关卡编辑器的代码分析, 在关卡编辑器开始时,使用mfc来初始化这个opengl这个驱动等等的处理 检测鼠标,键盘的输入,滑动等等 我自己自个划分的有 界面层 ,操作层,介质层 界面层 专门画显示界面的

tailiangliang的专栏 2068

uBlock-Origin-dev-filter高级使用技巧:如何自定义过滤规则和扩展功能

uBlock-Origin-dev-filter是一款强大的过滤工具,专为开发者设计,能够有效拦截和移除搜索引擎中GitHub、StackOverflow等开发类网站的克隆网站,提升搜索体验。本文将分享如何自定义过滤规则和扩展其功能,让你更精准地屏蔽不需要的内容。 ## 一、了解过滤规则的基本结构 uBlock-Origin-dev-filter的过滤规则基于特定的格式,主要通过域名匹配来实现

gitblog_00264的博客 954

qradiant(2)

关卡编辑器分析2 实在太长了,只能慢慢的修改了 对于这个surface这个曲面的系数,来进行这个surface这个的处理 可以来设置这个surface的系数了 对于parch这个的处理者也 做一个新的补丁者也,patch这个者也 还有这个选择模式下选择点,选择面,选择边等等的处理 转换为了这个选择模式,选择点,选择面,最后选择这个替换的纹理 关

tailiangliang的专栏 1309

VC++与GDI+图形编程:从核心原理到实战应用

在Windows桌面应用开发中,图形编程是实现数据可视化、界面美化和图像处理的基础能力。其核心原理在于通过图形设备接口与系统显示硬件进行交互,将抽象的绘图指令转化为屏幕上的像素。GDI+作为Windows平台经典的2D图形API,在易用性和功能丰富性之间取得了良好平衡,它提供了面向对象的编程模型,支持抗锯齿、渐变、透明混合等高级特性,显著提升了开发效率。从技术价值看,GDI+与VC++环境深度集成,能够充分发挥Windows原生特性,适合开发轻量级、高性能的桌面工具、工业控制软件和图形编辑器。在实际应用场景

cuiji1279的博客 361

git 全量同步分支

当前分支是maser分支,我想将stable分支上的代码完全覆盖brush分支,首先切换到brush分支。 git reset --hard origin/stable执行上面的命令后brush分支上的代码就完全被stable分支上的代码覆盖了(本地分支),然后将本地分支强行推到远程分支。 git push -f ...

tudounizi的博客 91

简单解释器

文章目录题目语法和语义循环绘图比例设置角度旋转坐标平移注释代码主函数功能函数头文件测试用例说明 题目 为函数绘图语言编写一个解释器,解释器接受用绘图语言编写的源程序,经语法和语义分析之后,将源程序所规定的图形显示在显示屏(或窗口)中。 语法和语义 循环绘图(FOR-DRAW) 比例设置(SCALE) 角度旋转(ROT) 坐标平移(ORIGIN) 注释 (-- 或 //) 循环绘图 ...

zev的博客 805

git常用命令

拉新某一分支 git fetch origin feature/ENG-930-reflect git checkout feature/ENG-930-reflect修改commit git rebase -i HEAD~2 输入i pick修改为edit, 修改commit信息 输入esc 输入:wq git commit --amend -m “Fix ENG-3804:sequence” git rebase --continue git push -f强制merge A分支合并B分支, 并强制使用

m0_47835669的博客 1440

Facial-Emotion-Detection图像预处理指南:224x224裁剪、归一化与BEiT特征提取流程深度解析

Facial-Emotion-Detection-FER-RAFDB-AffectNet-BEIT-Large 是基于 BEiT-Large 微调的**面部表情识别(Facial Emotion Detection)**模型,在 FER-2013、RAF-DB 与 AffectNet 三大人脸数据集上训练,可输出 7 种基本情绪:anger、disgust、fear、happy、neutral、s

gitblog_00263的博客 261
上一篇: Moving the Origin
下一篇: Seeing What You've Drawn
lemonade
博客等级 码龄26年 8粉丝 33原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值