按钮的背景图
private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
pictureBox1.Image = GetImageByIndex(DefImage, 1);
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
pictureBox1.Image = GetImageByIndex(DefImage, 2);
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
pictureBox1.Image = GetImageByIndex(DefImage, 1);
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
pictureBox1.Image = GetImageByIndex(DefImage, 0);
}
private Bitmap DefImage;
private void Form1_Load(object sender, EventArgs e)
{
DefImage = pictureBox1.Image as Bitmap;
pictureBox1.Image = GetImageByIndex(DefImage, 0);
}
private float _BgImageCount = 3;
public float BgImageCount
{
get { return _BgImageCount; }
set { _BgImageCount = value; }
}
/// <summary>
/// 通过索引获取裁剪后的图片,默认以水平获取
/// </summary>
/// <param name="bitmap">原图</param>
/// <param name="index">要获取的索引</param>
public Image GetImageByIndex(Bitmap bitmap, int index)
{
return GetImageByIndex(bitmap, index, true);
}
/// <summary>
/// 通过索引获取裁剪后的图片,
/// </summary>
/// <param name="bitmap"></param>
/// <param name="index"></param>
/// <param name="IsHorizontal">获取方式,以水平获取传True 否则传False</param>
public Image GetImageByIndex(Bitmap bitmap, int index, bool IsHorizontal)
{
return GetImageByIndex(bitmap, index, true, BgImageCount);
}
/// <summary>
/// 通过索引获取裁剪后的图片,
/// </summary>
/// <param name="bitmap"></param>
/// <param name="index"></param>
/// <param name="IsHorizontal">获取方式,以水平获取传True 否则传False</param>
/// <param name="bgImageCount">背景的个数</param>
public Image GetImageByIndex(Bitmap bitmap, int index, bool IsHorizontal, float bgImageCount)
{
Image img = bitmap;
float width, height;
if (IsHorizontal)
{
width = bitmap.Width / bgImageCount;
height = bitmap.Height;
img = ImageCut(bitmap, index * width, 0, width, height);
}
else
{
width = bitmap.Width;
height = bitmap.Height / bgImageCount;
img = ImageCut(bitmap, 0, index * height, width, height);
}
return img;
}
/// <summary>
///
/// </summary>
/// <param name="bitmap"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public Image ImageCut(Bitmap bitmap, float x, float y, float width, float height)
{
if (x + width > bitmap.Width)
{
width = bitmap.Width - x;
}
if (width <= 0)
{
width = bitmap.Width;
x = 0;
}
if (y + height > bitmap.Height)
{
height = bitmap.Height - y;
y = 0;
}
if (height <= 0)
{
height = bitmap.Height;
}
RectangleF rect = new RectangleF(x, y, width, height);
PixelFormat format = bitmap.PixelFormat;
Bitmap result = bitmap.Clone(rect, format);
return result;
}