Dynamic bitmaps are a solution that made PixiEditor work multiple times faster, decreased RAM usage by about 10 times and solved memory leak problems. This article will explain what dynamic bitmaps are and how they work.
Dynamic bitmaps have been introduced in a very early alpha (version v0.0.3), before that the PixiEditor image system was pretty straightforward.
Mouse clicks were converted into relative canvas coordinates, and then color was applied to the pixels at a given position. It was pretty simple, however, this solution had one big downside. PixiEditor uses WriteableBitmap to manipulate bitmaps and working on bigger canvases using this solution yielded bad performance and huge memory consumption.
So what was the solution? Dynamic bitmaps!
In simple words, a dynamic bitmap is a bitmap that fits the size of its content. This is crucial for the layer system. Here is a visual representation of how it works
Let's start with a simple algorithm
The process of resizing the bitmap is quite simple:
However, the implementation is not trivial, it requires some calculations, like extracting the border pixels, calculating offsets, checking if a coordinate is a border pixel and more.
Our algorithms look like this:
As you can see, the code is not trivial, it takes a lot of steps, our implementation also does a bit more stuff, like requesting clips (resizing whole document to perfectly fit the content) and clamping the maximum size.
Our implementation is very performant since we are using fast
BitmapContext.BlockCopy to copy and paste pixels into a new bitmap.
It's almost unnoticeable in real-time, with fast mouse movement small visual jittering can be visible, but there is no delay whatsoever. How fast dynamic bitmaps work, depends on the implementation, platform, native bitmap APIs, etc.
The benefits described below are not directly related to the implementation, but the usage of dynamic bitmaps.
These features are way easier to create (or possible at all), thanks to perfectly fitted bitmaps:
- Resize and rotate border,
- Clip canvas (fit document to content),
- Center content relative to document or other layers,
- Snapping and guides
- Efficient preview layers
Dynamic bitmaps are a very useful structure, it helps to create a lot of small bitmaps, which can be easily reused. No more unnecessary memory allocation and heavy CPU operations. If you want to learn more, join our Discord, we are open to discussions!