如何填充任意封闭区域.txt

来自「VB技巧问答10000例 VB技巧问答10000例」· 文本 代码 · 共 49 行

TXT
49
字号
FillColor属 性 用 在 VB中 绘 制 圆 和 矩 形 时 决 定 填 充 的 颜 色 。 如 果 想 填 充 任 意 区 域 要 借 助 Windows API。 Windows API中 有 两 组 用 于 填 充 , 一 组 是 利 用 区 域 函 数 , 另 一 组 是 利 用 ExtFloodFill函 数 。 
    Windows API允 许 使 用 CreatePolygonRgn等 函 数 创 建 区 域 , 可 以 是 矩 形 、 椭 圆 、 多 边 形 和 其 他 形 状 , 这 些 形 状 还 可 以 使 用 CombineRgn来 进 行 组 合 。 然 后 使 用 FillRgn进 行 填 充 。 下 面 给 出 一 个 简 单 的 例 子 , 使 用 FillRgn来 填 充 一 个 三 角 区 域 。 
    首 先 , 建 立 一 个 模 块 , 输 入 下 面 的 代 码 : 
    Type POINTAPI 
     x As Long 
     y As Long 
    End Type 
    Declare Function CreatePolygonRgn Lib "gdi32" (lpPoint As Any, ByVal nCount As Long, ByVal nPolyFillMode As Long) As Long 
    Declare Function Polygon Lib "gdi32" (ByVal hdc As Long, lpPoint As Any, ByVal nCount As Long) As Long 
    Declare Function FillRgn Lib "gdi32" (ByVal hdc As Long, ByVal hRgn As Long, ByVal hBrush As Long) As Long 
    Declare Function GetStockObject Lib "gdi32" (ByVal nIndex As Long) As Long 
    Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long 
    Public Const ALTERNATE = 1 ' ALTERNATE and WINDING are 
    Public Const WINDING = 2 ' constants for FillMode. 
    Public Const BLACKBRUSH = 4 
    然 后 在 Form中 输 入 以 下 代 码 , 这 样 每 次 你 单 击 窗 体 都 可 以 看 见 一 个 填 充 的 三 角 形 。 
    Private Sub Form_Click() 
     ' Dimension coordinate array. 
     ReDim poly(1 To 3) As POINTAPI 
     ' Number of vertices in polygon. 
     NumCoords = 3 
     ' Set scalemode to pixels to set up points of triangle. 
     Form1.ScaleMode = 3 
     ' Assign values to points. 
     poly(1).x = Form1.ScaleWidth / 2 
     poly(1).y = Form1.ScaleHeight / 2 
     poly(2).x = Form1.ScaleWidth / 4 
     poly(2).y = 3 * Form1.ScaleHeight / 4 
     poly(3).x = 3 * Form1.ScaleWidth / 4 
     poly(3).y = 3 * Form1.ScaleHeight / 4 
     ' Sets background color to White for contrast. 
     Form1.BackColor = vbWhite 
     ' Polygon function creates unfilled polygon on screen. 
     ' Remark FillRgn statement to see results. 
     bool = Polygon(Form1.hdc, poly(1), NumCoords) 
     ' Gets stock black brush. 
     hBrush = GetStockObject(BLACKBRUSH) 
     ' Creates region to fill with color. 
     hRgn = CreatePolygonRgn(poly(1), NumCoords, ALTERNATE) 
     ' If the creation of the region was successful then color. 
     If hRgn Then bool = FillRgn(Form1.hdc, hRgn, hBrush) 
     ' Print out some information. 
     Print "FillRgn Return : "; bool 
     Print "HRgn : "; hRgn 
     Print "Hbrush : "; hBrush 
     Trash = DeleteObject(hRgn) 
    End Sub 
    另 一 种 方 法 是 利 用 ExtFloodFill函 数 。 这 个 函 数 有 两 种 填 充 方 式 , 一 个 是 按 照 边 界 颜 色 填 充 区 域 , 另 一 个 是 将 一 种 颜 色 换 成 另 一 种 填 充 方 式 。 详 见 Windows API帮 助 。 
<END>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?