Skip to content

Advanced Retina/HiDPI: BitmapForCaching and ScaleFactorChanged

The most direct way to support HiDPI* for custom controls is to draw into the Graphics object passed into the Paint event. That graphics object is already configured with the appropriate scale factor and double buffering- the entire control will be handled correctly by the framework if the DoubleBuffer property is set.

*As with other posts, we’ll use “HiDPI” to refer to both HiDPI on Windows and Retina on OS X.

If drawing directly into the Graphics object passed into the control’€™s Paint event isn’€™t feasible or you need to manage your own caching of costly drawing for some reason, the BitmapForCaching function can be used to create a mutable bitmap that’s configured appropriately for using as a cache. This bitmap has some screen-specific properties, like the scale factor, and should be thrown away in the ScaleFactorChanged event. For example:

Class Foo
Inherits Canvas

Sub Paint(g As Graphics) Handles Event
CreateCacheIfNeeded()
g.DrawPicture(mCachedContent, 0, 0)
End Sub

Sub ScaleFactorChanged() Handles Event
mCachedContent = Nil
End Sub

Private Sub CreateCacheIfNeeded()
If mCachedContent <> Nil Then Exit Sub

// Pretend this is a costly operation
mCachedContent = Self.TrueWindow.BitmapForCaching(100, 100)
Dim g As Graphics = mCachedContent.Graphics
g.FillRect(0, 0, g.Width, g.Height)
End Sub

Private Dim mCachedContent As Picture
End Class