Best way to draw non-antialiased image with alpha support? Topic is solved

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
bluesnowball18
Earned a small fee
Earned a small fee
Posts: 13
Joined: Thu Apr 22, 2021 9:23 am

Best way to draw non-antialiased image with alpha support?

Post by bluesnowball18 »

Hello all.

I have a control derived from wxWindow with EVT_PAINT callback. I want to display an image according to the following requirements:
  1. It should support alpha channel on all platforms (at least on MSW, GTK+ and OSX wxWidgets builds);
  2. The image should be resized with nearest neighbor interpolation (again, on all platforms);
  3. The image will be changed frequently, so it should provide a fast access to raw pixel data.
The only solution I can think of is to use wxImage::Scale and then paint it through wxGraphicsContext::DrawBitmap:

Code: Select all

void Canvas::OnPaint(wxPaintEvent &event)
{
        wxAutoBufferedPaintDC dc(this);

        wxGraphicsContext *gc = wxGraphicsContext::Create(dc);

        if (gc != nullptr && this->image.IsOk()) {
                double w = this->image.GetWidth() * this->scale;
                double h = this->image.GetHeight() * this->scale;

                dc.Clear();

                gc->DrawBitmap(this->image.Scale(w, h, wxIMAGE_QUALITY_NEAREST),
                                0, 0, w, h);

                delete gc;
        }

        event.Skip();
}
But isn't that too expensive? The image scaled every time it painted, but the worst thing is, if the image is 2000*1000 px, scaling up 32 times gives 64000*32000 px image.
User avatar
doublemax
Moderator
Moderator
Posts: 19115
Joined: Fri Apr 21, 2006 8:03 pm
Location: $FCE2

Re: Best way to draw non-antialiased image with alpha support?

Post by doublemax »

Create a wxBitmap with explicit depth of 32.
Use wxPixelData to manipulate the wxBitmap data. https://docs.wxwidgets.org/trunk/classw ... _data.html
Use a "normal" wxDC and SetUserScale() to scale the bitmap while drawing.
Use the source, Luke!
PB
Part Of The Furniture
Part Of The Furniture
Posts: 4193
Joined: Sun Jan 03, 2010 5:45 pm

Re: Best way to draw non-antialiased image with alpha support?

Post by PB »

Or, do not scale the image during each repaint. Scale it only when the image size or the scale changes and store the scaled image.

Additionally, converting a wxImage to a wxGraphicBitmap can be expensive, so do not do that during every redraw either.
Post Reply