vendredi 25 juillet 2008

Comment afficher une image dans une wxGrid?

Ma grille de commerce sera bien plus jolie si elle contient des images. Cela tombe bien, wxGrid est très extensible, et tout plein de gens l'ont fait avant moi. Par contre, il m'a quand même fallu recoller les bouts!

La seule spécificité du code est le passage par un wxMemoryDC, qui permet donc de faire un blit exactement sur le rectangle au lieu de baver sur les autres cellules si l'on utilise tout bêtement un DrawBitmap.

Voilà le résultat:



Et voilà bien entendu le code.

wxBmpCellRenderer.h


/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
#include
#include

class wxBmpCellRenderer : public wxGridCellRenderer
{
public:
wxBmpCellRenderer(const wxBitmap & bmp);
void Draw(wxGrid& grid,
wxGridCellAttr& attr,
wxDC& dc,
const wxRect& rect,
int row,
int col,
bool isSelected);

wxSize GetBestSize(wxGrid& grid,
wxGridCellAttr& attr,
wxDC& dc,
int row,
int col);

wxGridCellRenderer *Clone() const;
private:
wxBitmap m_bmp;
};


wxBmpCellRenderer.cpp

/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
#include "wxBmpCellRenderer.h"

wxBmpCellRenderer::wxBmpCellRenderer(const wxBitmap & bmp):
m_bmp(bmp)
{
}

void wxBmpCellRenderer::Draw(wxGrid& grid,
wxGridCellAttr& attr,
wxDC& dc,
const wxRect& rect,
int row,
int col,
bool isSelected)
{
wxGridCellRenderer::Draw(grid,attr,dc,rect,row,col,isSelected);
wxMemoryDC memdc;
memdc.SelectObject(m_bmp);
dc.Blit(rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight(),
&memdc, 0, 0);
}

wxSize wxBmpCellRenderer::GetBestSize(wxGrid& grid,
wxGridCellAttr& attr,
wxDC& dc,
int row,
int col)
{
return wxSize(m_bmp.GetWidth(), m_bmp.GetHeight());
}

wxGridCellRenderer * wxBmpCellRenderer::wxBmpCellRenderer::Clone() const
{
return new wxBmpCellRenderer(m_bmp);
}

Aucun commentaire: