背景图片随子文字组件的宽度变化

 

为了适配中英文字符长度,背景图长度也拉伸

 

 

 

1.背景图锚点设置,文字需左对齐,所以锚点设置相同

 

 

2.文字添加ContentSizeFitter,保证文字改变时宽度也改变

 

3.设置背景图宽度

private void BGFitCharLength()
{
var tip_rect = m_pwd_tip.GetComponent<RectTransform>();
TMP_Text[] text_ui = m_pwd_tip.GetComponentsInChildren<TMP_Text>(true);
float max_width = 0;
foreach (var t in text_ui)
{
if (t.preferredWidth > max_width)
{
max_width = t.preferredWidth;//添加ContentSizeFitter后必须用preferredWidth,rect.sizeDelta.x和rect.rect.width都不行,取出来是0
}
}
tip_rect.sizeDelta = new Vector2(max_width + 68, tip_rect.sizeDelta.y);
}

 

posted @ 2022-06-22 20:20  alps_01  阅读(94)  评论(0编辑  收藏  举报