1、创建一个 Graphics object
2、使用这个Graphics object 画线,画矩形,画图片等
具体代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private Rectangle RcDraw;
private float PenWidth = 5;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
RcDraw.X = e.X;
RcDraw.Y = e.Y;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
// Determine the width and height of the rectangle...
if (e.X < RcDraw.X)
{
RcDraw.Width = RcDraw.X - e.X;
RcDraw.X = e.X;
}
else
{
RcDraw.Width = e.X - RcDraw.X;
}
if (e.Y < RcDraw.Y)
{
RcDraw.Height = RcDraw.Y - e.Y;
RcDraw.Y = e.Y;
}
else
{
RcDraw.Height = e.Y - RcDraw.Y;
}
// Force a repaint of the region occupied by the rectangle...
this.Invalidate(RcDraw);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Create image.
Image imageFile = Image.FromFile(@"D:\MFCCode\WindowsFormsApp1\WindowsFormsApp1\10.jpg");
// Create graphics object for alteration.
Graphics newGraphics = Graphics.FromImage(imageFile);
// Alter image.
newGraphics.FillRectangle(new SolidBrush(Color.Black), 100, 50, 100, 100);
// Draw image to screen.
e.Graphics.DrawImage(imageFile, new PointF(0.0F, 0.0F));
// Dispose of graphics object.
newGraphics.Dispose();
// Draw the rectangle...
e.Graphics.DrawRectangle(new Pen(Color.Blue, PenWidth), RcDraw);
}
}
}