编辑
2025-09-26
C#
00

目录

摘要
正文
Graphics类
示例1:绘制一个红色矩形
示例2:绘制一个虚线矩形
示例3:绘制一个库存图

摘要

在C#开发中,GDI+是一个强大的图形库,可以用来创建各种图形和图像。本文将介绍如何使用GDI+在C#中绘制长方形,并详细讨论常用的方法与属性。

正文

Graphics类

在GDI+中,我们使用Graphics类来进行图形绘制。以下是一些常用的Graphics类方法和属性,用于绘制长方形:

  1. DrawRectangle():这个方法用于绘制一个矩形,您可以指定矩形的位置、大小、颜色等参数。
  2. FillRectangle():与DrawRectangle()类似,但用于填充矩形内部的颜色。

示例1:绘制一个红色矩形

C#
private void DrawRedRectangle() { using (Graphics g = this.CreateGraphics()) { Pen pen = new Pen(Color.Red, 2); g.DrawRectangle(pen, 50, 50, 100, 80); } }

示例2:绘制一个虚线矩形

C#
private void DrawDashedRectangle() { using (Graphics g = this.CreateGraphics()) { Pen pen = new Pen(Color.Green, 2); pen.DashStyle = DashStyle.Dash; g.DrawRectangle(pen, 250, 250, 80, 60); } }

示例3:绘制一个库存图

C#
public partial class Form1 : Form { private Rectangle[] inventoryLocations; public Form1() { InitializeComponent(); this.Text = "库存库位图"; this.Size = new Size(800, 600); this.inventoryLocations = new Rectangle[20]; // 假设有10个库位 // 初始化库位位置和状态 InitializeInventoryLocations(); this.Paint += new PaintEventHandler(InventoryLocationMap_Paint); } private void InitializeInventoryLocations() { // 假设库位状态为:0表示空闲、1表示已使用、2表示损坏 int[] locationStatus = { 0, 1, 0, 1, 2, 0, 0, 1, 0, 1,0, 1, 0, 1, 2, 0, 0, 1, 0, 1 }; int locationWidth = 50; int locationHeight = 50; int startX = 50; int startY = 50; for (int i = 0; i < this.inventoryLocations.Length; i++) { int x = startX + (i % 5) * (locationWidth + 10); int y = startY + (i / 5) * (locationHeight + 10); this.inventoryLocations[i] = new Rectangle(x, y, locationWidth, locationHeight); } } private void InventoryLocationMap_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; for (int i = 0; i < this.inventoryLocations.Length; i++) { Rectangle location = this.inventoryLocations[i]; // 根据库位状态绘制不同颜色的矩形 if (i % 3 == 0) { g.FillRectangle(Brushes.Green, location); } else if (i % 3 == 1) { g.FillRectangle(Brushes.Blue, location); } else { g.FillRectangle(Brushes.Red, location); } g.DrawRectangle(Pens.Black, location); } } }

image.png

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!