(C#)在窗口中绘制图片myDrawImageA
//实现功能:在窗口中绘制图片
//要点:
//通过创建图形类,实现图片的读取和绘制;
//控件背景绘制模式(透明与否);
//指定图片显示区域的位置和大小;
//在窗体的dispose()中加入释放图形类变量的代码(很重要)[窗体的dispose()在Form1.Designer.cs中]
FORM1.CS文件代码如下(红字为新添加):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace myDrawImageA
{
public
partial class Form1 :
Form
{
private Image
myImageA;//声明一个图形类变量
public
Form1()
{
InitializeComponent();
//
SetStyle(ControlStyles.Opaque, true); //在窗口构造函数中指定有关透明与否的控件绘制模式样式
SetStyle(ControlStyles.Opaque,
false);
//
myImageA = new
Bitmap(myDrawImageA.Properties.Resources.PRINT1);
//读取事先已加入资源的位图(将位图加入资源的方法参见“myMenuA"将图标加入资源的方法)
}
protected override void
OnPaint(PaintEventArgs e)
{
//base.OnPaint(e);
Graphics g = e.Graphics;
//g.DrawImage(myImageA,
ClientRectangle);//将图绘制在整个客户区(图形大小随客户区)
Rectangle myRec = new Rectangle(10, 10, 100, 100);
//指定显示区域的位置的大小
g.DrawImage(myImageA, myRec);
}
}
}
Form1.Designer.cs文件代码如下(红字为新添加):
namespace myDrawImageA
{
partial
class Form1
{
/// <summary>
///
必需的设计器变量。
/// </summary>
private
System.ComponentModel.IContainer
components = null;
/// <summary>
///
清理所有正在使用的资源。
/// </summary>
/// <param
name="disposing">如果应释放托管资源,为
true;否则为 false。</param>
protected
override void Dispose(bool disposing)
{
if
(Disposing)
//释放
{
//
myImageA.Dispose(); //
}
//
if (disposing
&& (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
///
设计器支持所需的方法
-
不要
///
使用代码编辑器修改此方法的内容。
/// </summary>
private
void
InitializeComponent()
{
this.SuspendLayout();
//
//
Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode =
System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize =
new System.Drawing.Size(425, 266);
this.Name =
"Form1";
this.Text =
"Form1";
this.ResumeLayout(false);
}
#endregion
}
}