我们知道,在Windows Mobile开发过程中,控件远没有开发Web、WinForm的控件库多。有的只是一些普通的常见控件,为了提高体验效果。我们需要动一些功夫了.........
在WM中,有button这个基本的按钮。让她如何变成图片按钮呢,这里要用到继承。然后要用到Drawing下面的一些类按照图片的形状进行绘制。
class PictureButton : Control //继承
{
private Image image;
private bool bPushed;
private Bitmap m_bmpOffscreen;
public PictureButton()
{
bPushed = false;
this.Size = new Size(40, 40);//初始化
}
public Image Image
{
get
{
return image;
}
set
{
image = value;
}
}
//重绘
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
Graphics gxOff;
Rectangle imgRect;
Brush backBrush;
SolidBrush drawBrush = new SolidBrush(this.ForeColor);
string disPlayText = this.Text;
StringFormat drawFormat = new StringFormat();
drawFormat.FormatFlags = StringFormatFlags.NoWrap;
drawFormat.LineAlignment = StringAlignment.Center;
drawFormat.Alignment = System.Drawing.StringAlignment.Center;
if (m_bmpOffscreen == null)
{
m_bmpOffscreen = new Bitmap(ClientSize.Width, ClientSize.Height);
}
gxOff = Graphics.FromImage(m_bmpOffscreen);
gxOff.Clear(this.BackColor);
if (!bPushed)
backBrush = new SolidBrush(Parent.BackColor);
else
backBrush = new SolidBrush(Parent.BackColor);
gxOff.FillRectangle(backBrush, this.ClientRectangle);
if (image != null)
{
int imageLeft = (this.Width - image.Width) / 2;
// int imageTop = (this.Height - image.Height) / 2;
int imageTop = 1;
if (!bPushed)
{
imgRect = new Rectangle(imageLeft, imageTop, image.Width,
image.Height);
}
else
{
imgRect = new Rectangle(imageLeft+1,imageTop+1, image.Width, image.Height);
}
ImageAttributes imageAttr = new ImageAttributes();
imageAttr.SetColorKey(BackgroundImageColor(image),
BackgroundImageColor(image));
gxOff.DrawImage(image, imgRect, 0, 0, image.Width, image.Height,
GraphicsUnit.Pixel, imageAttr);
}
if (bPushed) //按钮被按下时效果
{
Rectangle rc = this.ClientRectangle;
rc.Width--;
rc.Height--;
gxOff.DrawRectangle(new Pen(this.BackColor), rc);
}
gxOff.DrawString(disPlayText, this.Font, drawBrush, 0, 32);
e.Graphics.DrawImage(m_bmpOffscreen, 0, 0);
base.OnPaint(e);
}
private Color BackgroundImageColor(Image image)
{
Bitmap bmp = new Bitmap(image);
return bmp.GetPixel(0, 0);
}
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
bPushed = true;
this.Invalidate();
}
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
{
bPushed = false;
this.Invalidate();
}
}//end PictureButton
Ok,目前为止,这个图片按钮已经绘制完成了,如果各位有更好的方法欢迎指点一二,本人现在正在搞WM开发,由于是新手,难免有不足
期待着各位的意见!Thank you!!
virgree 2010/5/23/9:42