VGUI ImageButton

From Valve Developer Community
Revision as of 19:22, 2 June 2009 by Brian4 (talk | contribs)
Jump to navigation Jump to search
class ImageButton : public vgui::ImagePanel
{
private:
	DECLARE_CLASS_SIMPLE( ImageButton, vgui::ImagePanel );
	char command[32];
	vgui::IImage *i_normalImage;
	vgui::IImage *i_mouseOverImage;
	vgui::IImage *i_mouseClickImage;
	char m_normalImage[32];
	char m_mouseOverImage[32];
	char m_mouseClickImage[32];

	bool hasCommand;
	bool hasMouseOverImage;
	bool hasMouseClickImage;

	virtual void SetImage( vgui::IImage *image )
	{
		BaseClass::SetImage( image );
	}

public:
	ImageButton( Panel *parent, const char *panelName, const char *normalImage, const char *mouseOverImage = NULL, const char *mouseClickImage = NULL, const char *pCmd=NULL ) : vgui::ImagePanel( parent, panelName ) 
	{
		if ( pCmd != NULL )
		{
			Q_strcpy( command, pCmd );
			hasCommand = true;
		}
		else
			hasCommand = false;

		Q_strcpy( m_normalImage, normalImage );
		i_normalImage = vgui::scheme()->GetImage( m_normalImage, false );

		if ( mouseOverImage != NULL )
		{
			Q_strcpy( m_mouseOverImage, mouseOverImage );
			i_mouseOverImage = vgui::scheme()->GetImage( m_mouseOverImage, false );
			hasMouseOverImage = true;
		}
		else
			hasMouseOverImage = false;

		if ( mouseClickImage != NULL )
		{
			Q_strcpy( m_mouseClickImage, mouseClickImage );
			i_mouseClickImage = vgui::scheme()->GetImage( m_mouseClickImage, false );
			hasMouseClickImage = true;
		}
		else
			hasMouseClickImage = false;

		SetNormalImage();
	}

	virtual void OnCursorEntered()
	{
		if ( hasMouseOverImage )
			SetMouseOverImage();
	}

	virtual void OnCursorExited()
	{
		if ( hasMouseOverImage )
			SetNormalImage();
	}

	virtual void OnMouseReleased( vgui::MouseCode code )
	 {
		 Panel *parentPanel = GetParent();
		 parentPanel->OnCommand( command );

		 if ( ( code == MOUSE_LEFT ) && hasMouseClickImage )
			SetNormalImage();
	 }

	 virtual void OnMousePressed( vgui::MouseCode code )
	 {
		if ( ( code == MOUSE_LEFT ) && hasMouseClickImage )
			SetMouseClickImage();
	 }

	void SetNormalImage( void )
	{
		SetImage(i_normalImage);
		Repaint();
	}

	void SetMouseOverImage( void )
	{
		SetImage(i_mouseOverImage);
		Repaint();
	}

};


This class allows you to create buttons, that are images. Depending upon what you pass in the constructor, this 'imagebutton' will change its image if your mouse hovers over it, or you click on it, and then change back when your mouse moves away from it, or you finish clicking.

This code written by brian4.

TODO: Make this more wiki compatable as well as put part of it in a cpp file, the rest in a header file.