1+ @file:Suppress(" ConstPropertyName" )
2+
3+ package com.reco1l.andengine
4+
5+ import android.content.Context
6+ import android.graphics.Color
7+ import android.graphics.Typeface
8+ import android.util.Log
9+ import com.reco1l.andengine.component.UIComponent
10+ import org.anddev.andengine.opengl.font.Font
11+ import org.anddev.andengine.opengl.texture.TextureOptions
12+ import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas
13+ import org.anddev.andengine.opengl.util.GLHelper
14+ import java.lang.ref.WeakReference
15+
16+ class UIResourceManager (private val context : Context ) {
17+
18+ private val fonts = mutableMapOf<String , Font >()
19+ private val fontSubscribers = mutableMapOf<Font , MutableList <WeakReference <UIComponent >>>()
20+
21+
22+ fun getOrStoreFont (size : Float , family : String ): Font {
23+
24+ val fontIdentifier = " ${family} -${size} "
25+
26+ val fetchedFont = fonts[fontIdentifier]
27+ if (fetchedFont != null ) {
28+ return fetchedFont
29+ }
30+
31+ Log .i(" UIResourceManager" , " Loading font: $fontIdentifier with texture size ${GLHelper .GlMaxTextureWidth / 2 } x${GLHelper .GlMaxTextureWidth / 2 } " )
32+
33+ val texture = BitmapTextureAtlas (
34+ GLHelper .GlMaxTextureWidth / 2 ,
35+ GLHelper .GlMaxTextureWidth / 2 ,
36+ TextureOptions .BILINEAR_PREMULTIPLYALPHA
37+ )
38+ val typeface = Typeface .createFromAsset(context.assets, " fonts/${family} " )
39+ val font = Font (texture, typeface, size, true , Color .WHITE )
40+
41+ UIEngine .current.apply {
42+ textureManager.loadTexture(texture)
43+ fontManager.loadFont(font)
44+
45+ fonts[fontIdentifier] = font
46+ }
47+
48+ return font
49+ }
50+
51+ fun subscribeToFont (font : Font , component : UIComponent ) {
52+ val subscribers = fontSubscribers.getOrPut(font) { mutableListOf () }
53+ if (subscribers.none { it.get() == = component }) {
54+ subscribers.add(WeakReference (component))
55+ }
56+ }
57+
58+ fun unsubscribeFromFont (font : Font , component : UIComponent ) {
59+
60+ val subscribers = fontSubscribers[font] ? : return
61+ subscribers.removeAll { it.get() == = component || it.get() == null }
62+
63+ if (subscribers.isEmpty()) {
64+ val fontKey = fonts.entries.find { it.value == font }?.key
65+ Log .i(" UIResourceManager" , " Unloading font: $fontKey " )
66+
67+ fonts.remove(fontKey)
68+ fontSubscribers.remove(font)
69+
70+ UIEngine .current.apply {
71+ fontManager.unloadFont(font)
72+ textureManager.unloadTexture(font.texture)
73+ }
74+ }
75+ }
76+
77+ }
0 commit comments