C#控件开发-GDI编程

C# 控件开发-GDI编程

C# Winform原生控件产值是拿不出手的,工控环境对界面要求不高可以将就,稳定就好。然而更多时候需要美化,这里只研究如何美化。

什么是GDI

控件美化少不了GDI+编程基础,GDI+(Graphics Device Interface)是一种绘图装置接口,可将应用程序和绘图硬件分隔,让我们能够编写与装置无关的应用程序。只需要调用GDI提供的API函数绘制一系列图形。

C#使用System.Drawing命名空间和Graphics绘图类,官方api地址:https://learn.microsoft.com/zh-cn/dotnet/api/system.drawing.graphics?view=netframework-4.8。其中列举了一系列的绘图方法。

绘图坐标系

GDI绘图使用坐标系,原点在控件左上角,向右为x轴正方向,向下为y轴正方向。

绘图事件

.Net 控件Control类提供一个OnPaint事件,用于控件绘图使用。
新建一个窗体项目,在属性窗体中找到paint事件,双击自动生成窗体的paint事件代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 绘图事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;

            Rectangle rect = new Rectangle(500, 100, 200, 50);

            Rectangle fillRect = new Rectangle(50, 60, 100, 100);
            //使用using自动释放Pen
            using (Pen p = new Pen(Color.Red, 3))
            {
                // 画线
                g.DrawLine(p, 0, 0, 300, 100);

                // 换一种颜色画个矩形
                p.Color = Color.FromArgb(200, 200, 200);
                // 坐标点(50,60)处画个100*100矩形
                g.DrawRectangle(p, fillRect);

                // 画椭圆
                p.Color = Color.FromArgb(0, 200, 200);
                g.DrawEllipse(p, new Rectangle(50, 200, 100, 100));
                
                // 带文字的框
                p.Color = Color.FromArgb(0, 0, 0);
                g.DrawRectangle(p, rect);
            }


            using (SolidBrush sb = new SolidBrush(Color.FromArgb(100, 110, 220)))
            {
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                g.DrawString("GDI绘图", this.Font, sb, new PointF(500,300),sf);

                g.DrawString("矩形中居中的文字", this.Font, sb, rect, sf);

                g.FillRectangle(sb, fillRect);
            }
        }
    }
}

效果如图
在这里插入图片描述

这些画图API函数可以基本满足控件绘图需要

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值