File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -19,8 +19,18 @@ pub struct Text {
1919 pub pos : KdlPos2 ,
2020 #[ knus( child, unwrap( argument) , default = String :: new( ) ) ]
2121 pub val : String ,
22- pub position : Pos2 ,
23- pub content : String ,
22+
23+ text_width : std:: sync:: OnceLock < f32 > ,
24+ }
25+ impl Text {
26+ pub fn new ( id : String , pos : Pos2 , val : String ) -> Self {
27+ Text {
28+ id,
29+ pos : pos. into ( ) ,
30+ val,
31+ text_width : std:: sync:: OnceLock :: new ( ) ,
32+ }
33+ }
2434}
2535impl EntityTrait for Text {
2636 fn id ( & self ) -> & str {
Original file line number Diff line number Diff line change 1- use egui:: { Context , FontId , Painter } ;
2- use lru:: LruCache ;
3- use std:: num:: NonZeroUsize ;
4- use std:: sync:: { LazyLock , Mutex } ;
5-
6- #[ derive( Hash , PartialEq , Eq , Clone ) ]
7- struct TextWidthCacheKey {
8- text : String ,
9- /// 浮点数不能作为哈希键,所以需要转换为整数后存储
10- size : i32 ,
11- }
12-
13- static TEXT_WIDTH_CACHE : LazyLock < Mutex < LruCache < TextWidthCacheKey , f32 > > > = LazyLock :: new ( || {
14- let cache = LruCache :: new ( NonZeroUsize :: new ( 1024 ) . unwrap ( ) ) ;
15- Mutex :: new ( cache)
16- } ) ;
1+ use egui:: { FontId , Painter } ;
172
183/// 计算文字宽度
194pub fn get_text_width ( text : & str , font_size : f32 , painter : & Painter ) -> f32 {
20- let key = TextWidthCacheKey {
21- text : text. to_string ( ) ,
22- size : ( font_size * 10.0 ) as i32 ,
23- } ;
24-
25- if let Ok ( mut cache) = TEXT_WIDTH_CACHE . lock ( ) {
26- if let Some ( & width) = cache. get ( & key) {
27- return width;
28- }
29- }
30-
315 let font_id = FontId :: proportional ( font_size) ;
326 let galley = painter. layout_no_wrap ( text. to_string ( ) , font_id, egui:: Color32 :: TRANSPARENT ) ;
33- let width = galley. size ( ) . x ;
34-
35- if let Ok ( mut cache) = TEXT_WIDTH_CACHE . lock ( ) {
36- cache. put ( key, width) ;
37- }
38-
39- width
7+ galley. size ( ) . x
408}
You can’t perform that action at this time.
0 commit comments