블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2737)
Unity3D (817)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-21 00:01

Unity 2021.3.33f1

NGUI 2023.08.01

----

 

NGUI-UILabel의 Effect에서 Shadow와 Outline을 같이 적용하고 싶어서 찾아보고 올려둠.

UILabel에 세 곳에 소스 추가

public class UILabel : UIWidget
{
    ....
    
    [DoNotObfuscateNGUI] public enum Effect
    {
        None,
        Shadow,
        Outline,
        Outline8,
        ShadowAndOutline,	// Add
    }   
    
    ....
    
    /// <summary>
    /// How many quads there are per printed character.
    /// </summary>

    public int quadsPerCharacter
    {
        get
        {
            if (mEffectStyle == Effect.Shadow) return 2;
            else if (mEffectStyle == Effect.Outline) return 5;
            else if (mEffectStyle == Effect.Outline8) return 9;
            else if (mEffectStyle == Effect.ShadowAndOutline) return 9;	// Add
            return 1;
        }
    }

	....
    
    public void Fill (List<Vector3> verts, List<Vector2> uvs, List<Color> cols, List<Vector3> symbolVerts, List<Vector2> symbolUVs, List<Color> symbolCols)
	{
        ...
        // Apply an effect if one was requested
		if (effectStyle != Effect.None)
		{
			int end = verts.Count;
			var symEnd = (symbolVerts != null) ? symbolVerts.Count : 0;

			pos.x = mEffectDistance.x;
			pos.y = mEffectDistance.y;

			ApplyShadow(verts, uvs, cols, offset, end, pos.x, -pos.y);
			if (symbolVerts != null) ApplyShadow(symbolVerts, symbolUVs, symbolCols, symOffset, symEnd, pos.x, -pos.y);

            #region Add ShadowAndOutline
            if (effectStyle == Effect.ShadowAndOutline)
            {
                pos.y /= 2;
                pos.x = pos.y;

                offset = end;
                end = verts.Count;

                ApplyShadow(verts, uvs, cols, offset, end, -pos.x, pos.y);

                offset = end;
                end = verts.Count;

                ApplyShadow(verts, uvs, cols, offset, end, pos.x, pos.y);

                offset = end;
                end = verts.Count;

                ApplyShadow(verts, uvs, cols, offset, end, -pos.x, -pos.y);

                offset = end;
                end = verts.Count;

                ApplyShadow(verts, uvs, cols, offset, end, -pos.x, 0);

                offset = end;
                end = verts.Count;

                ApplyShadow(verts, uvs, cols, offset, end, pos.x, 0);

                offset = end;
                end = verts.Count;

                ApplyShadow(verts, uvs, cols, offset, end, 0, pos.y);

                offset = end;
                end = verts.Count;

                ApplyShadow(verts, uvs, cols, offset, end, 0, -pos.y);
            }
			#endregion

            if ((effectStyle == Effect.Outline) || (effectStyle == Effect.Outline8))
			{        
        ...
    }
	
}

 

 

[출처] https://gamedev.stackexchange.com/questions/151329/all-sides-shadow-outline-in-unity-ngui

 

All sides shadow outline in Unity NGUI

How can I make such exactly the same shadow using NGUI?

gamedev.stackexchange.com

 

반응형
Posted by blueasa
, |

Unity 2021.3.14f1

NGUI 2022.06.08

 

NGUI의 UILabel에 있는 Dynamic Font 글자 사용시 가끔 글자가 깨졌다가 돌아오는 현상이 있어서 수정함.

 

UILabel에서 글자가 깨지는 이유는 Dynamic Font Texture 사이즈가 256x256을 기본으로 쓰다가,

텍스쳐 사이즈가 모자라면 512x512로 늘리는데 사이즈가 변경되는 시점에 잠시 글자가 깨졌다가 보이게 된다고 한다.

그래서 사이즈 변경할 필요 없게 사용하는 폰트의 글자를 모두 로드해 버리기로 했다.

(아래 첨부된 txt 파일의 글자를 로드하니 2048x2048이 나온다. 처음부터 로드하고 써버리기로 함.)

 

아래 [참조]링크의 소스를 참조해서 정리해서 아래와 같이 FontManager에 적용했다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FontManagerSGT : MonoSingleton<FontManagerSGT>
{
    public delegate void OnChangeFontDelegate(eLanguage _eLanguage);
    public static event OnChangeFontDelegate OnChangeFontEvent;

    public NGUIFont m_nguiFontMain_Dynamic;
    public Font m_fontMain_GO;  // Global
    public Font m_fontMain_JA;  // Japan

    private eLanguage m_eLanguage_Prev = eLanguage.None;
    private eLanguage m_eLanguage_Current = eLanguage.None;

    private string m_strReferenceTxt_GO = null;
    private string m_strReferenceTxt_JA = null;
    private Texture m_textureFontMainTexture = null;
    private TextAsset m_textReferenceTxt = null;


    void Start()
    {
        SetDontDestroy();
    }

    void OnEnable()
    {

    }

    void OnDisable()
    {

    }

    public void SetFont(eLanguage _eLanguage)
    {
        // 폰트매니저용 언어로 변경(JA 외는 GO(글로벌)로 변환)
        m_eLanguage_Current = GetLanguageForFont(_eLanguage);

        ChangeFont(m_eLanguage_Current);
        m_eLanguage_Prev = m_eLanguage_Current;
    }

    public eLanguage GetLanguageForFont(eLanguage _eLanguage)
    {
        switch (_eLanguage)
        {
            // Japan
            case eLanguage.JA:
                return eLanguage.JA;

            // Global(Less)
            default:
                return eLanguage.GO;
        }
    }

    void ChangeFont(eLanguage _eLanguage)
    {
        Debug.LogFormat("[eLanguage] [Prev] {0} [Current] {1}", m_eLanguage_Prev, _eLanguage);

        // 같은 폰트면 Pass
        if (m_eLanguage_Prev == _eLanguage)
            return;

        Debug.Assert(null != m_nguiFontMain_Dynamic);
        Debug.Assert(null != m_fontMain_GO);
        Debug.Assert(null != m_fontMain_JA);

        switch (_eLanguage)
        {
            // Japan
            case eLanguage.JA:
                {
                    m_nguiFontMain_Dynamic.dynamicFont = m_fontMain_JA;
                    FixBrokenWord_JA();
                }
                break;

            // Global(Less)
            default:
                {
                    m_nguiFontMain_Dynamic.dynamicFont = m_fontMain_GO;
                    FixBrokenWord_GO();
                }
                break;
        }

        OnChangeFontEvent?.Invoke(_eLanguage);
    }

    void FixBrokenWord_JA()
    {
        if (m_strReferenceTxt_JA == null)
        {
            m_textReferenceTxt = Resources.Load("ReferenceTxt/ja") as TextAsset;
            if (null != m_textReferenceTxt)
            {
                m_strReferenceTxt_JA = m_textReferenceTxt.ToString();
            }
        }

        if (null != m_strReferenceTxt_JA)
        {
            m_fontMain_JA.RequestCharactersInTexture(m_strReferenceTxt_JA);
            m_textureFontMainTexture = m_fontMain_JA.material.mainTexture; // Font 내부 텍스쳐
            Debug.LogWarning(string.Format("[m_strReferenceTxt_JA] texture : {0}x{1}", m_textureFontMainTexture.width, m_textureFontMainTexture.height)); // 텍스쳐 크기
        }
        else
        {
            Debug.LogWarning("m_strReferenceTxt_JA is null");
        }
    }

    void FixBrokenWord_GO()
    {
        if (m_strReferenceTxt_GO == null)
        {
            m_textReferenceTxt = Resources.Load("ReferenceTxt/go") as TextAsset;
            if (null != m_textReferenceTxt)
            {
                m_strReferenceTxt_GO = m_textReferenceTxt.ToString();
            }
        }

        if (null != m_strReferenceTxt_GO)
        {
            m_fontMain_GO.RequestCharactersInTexture(m_strReferenceTxt_GO);
            m_textureFontMainTexture = m_fontMain_GO.material.mainTexture; // Font 내부 텍스쳐
            Debug.LogWarning(string.Format("[m_fontMain_GO] texture : {0}x{1}", m_textureFontMainTexture.width, m_textureFontMainTexture.height)); // 텍스쳐 크기
        }
        else
        {
            Debug.LogWarning("m_strReferenceTxt_GO is null");
        }
    }
}

 

GO(Global)는 JA(일본어)를 제외한 모든 폰트를 합친 글로벌용 폰트이다.

일본어 한자가 중국어(번체)(대만)와 ASCII 코드가 겹치는 문제로 폰트 자체를 분리했다.

 

소스상에서 Resources.Load 하고 있는 go.txt와 ja.txt는 아래 올려둔다.

폰트를 2개로 분리해놔서 해당 폰트 사용 시, 맞는 txt를 로드하기 위해 Load 파일도 2개이다.

 

첨부된 파일은 폰트 병합 할 때 쓰는 참조용 데이터이기 때문에 모두 로드하면 폰트에 있는 모든 글자를 쓰게 되므로 이걸 로드해서 쓰게되면 더이상 텍스쳐가 커질일은 없을거라 예상된다.

 

 

[폰트 텍스쳐 확장을 위한 참조용 txt 파일]

go.txt
0.03MB
ja.txt
0.01MB

 

 

[참조] https://blueasa.tistory.com/2688

 

[펌] Unity 동적 글꼴 텍스트 깨짐 솔루션(Dynamic Font Broken)

Unity의 동적 글꼴을 사용하여 텍스트를 그릴 때 두 개의 UI 인터페이스가 열리면 그 뒤에 있는 텍스트가 깨집니다(완전히 엉망이 됨). 내가 사용하는 UI 플러그인은 Daikon Forge입니다. 라벨 업데이

blueasa.tistory.com

[참조2] https://blueasa.tistory.com/2664

 

[펌] NGUI - Dynamic Font 글자 깨짐? 사라짐? 현상

게임도중 핸드폰에서 Home 키를 눌러 배경화면으로 이동 후 Server와 끊기기를 기다리고 다시 Server와 리커넥팅 되도록 해서 팝업 떴는데.. Font가 깨졌다. 뭐지.. .... UILabel 에서 DynamicFont 가 이상한

blueasa.tistory.com

 

반응형
Posted by blueasa
, |

프로젝트는 NGUI를 사용하며 최근에 로딩 인터페이스의 프롬프트 텍스트가 깨지는 버그가 발생했습니다.


다음 기사를 참조했습니다.

http://blog.csdn.net/langresser_king/article/details/22095235

이 문제가 발생하는 이유를 먼저 이해합시다.



이해해야 할 것은 NGUI의 UILabel은 Unity에서 제공하는 글꼴을 글꼴의 입력으로 사용한다는 것입니다.

Unity는 글꼴 생성에 대해 매우 경제적이며 이는 정상적인 엔진이며 엔진은 이와 같아야 합니다.



(1) Loading 인터페이스의 UILabel에 세 단어 로딩을 표시하면 Unity가 이 세 단어의 텍스처를 생성하고 128x128의 FontTexture가 충분해야 합니다. 그런 다음 UILabel은 글꼴에 따라 각 단어의 그래픽을 가져옵니다.



(2) 그런 다음 다른 인터페이스를 열고 이 인터페이스에 많은 문자가 있을 때 128x128 FontTexture가 충분하지 않으면 Unity는 새 FontTexture를 생성하고 콜백을 발생시킵니다.

(3) 그런 다음 NGUI의 UILabel에서 이 콜백을 처리하고 모든 UILabel을 트래버스하고 UILabel의 모든 내용을 Font에 푸시하여 FontTexture에 대한 새 텍스트 그래픽을 생성합니다.

static BetterList<UILabel> mList = new BetterList<UILabel>();
protected override void OnInit ()
{
    base.OnInit();
    mList.Add(this);
    SetActiveFont(trueTypeFont);
}

 

//每次新建一个UILabel,都会读取UILabel上面的内容,在FontTexture上添加一块字体纹理。当FontTexture超过了原来的大小时,就会抛弃原来的FontTexture,用一个新的FontTexture,然后遍历所有的UILabel,往新的FontTexture上添加字体纹理。
static void OnFontTextureChanged ()
{
    for (int i = 0; i < mList.size; ++i)
    {
        UILabel lbl = mList[i];
 
        if (lbl != null)
        {
            Font fnt = lbl.trueTypeFont;
 
            if (fnt != null)
            {
                fnt.RequestCharactersInTexture(lbl.mText, lbl.mPrintedSize, lbl.mFontStyle);
            }
        }
    }
 
    //这段代码让UILabel重新读取UV 重新渲染,下一帧文字就是正常的了
    for (int i = 0; i < mList.size; ++i)
    {
        UILabel lbl = mList[i];
 
        if (lbl != null)
        {
            Font fnt = lbl.trueTypeFont;
 
            if (fnt != null)
            {
                lbl.RemoveFromPanel();
                lbl.CreatePanel();
            }
        }
    }
}


(4) 마지막으로 UILabel이 다시 렌더링됩니다.

깨진 글꼴은 (2)에서 나타납니다 UILabel이 이미 렌더링 중일 때 Unity는 새 FontTexture를 생성하므로 현재 프레임에 표시되는 그래픽에 문제가 있을 것입니다.

해결책은 게임의 모든 캐릭터를 포함하여 처음에 글꼴에 충분한 텍스트를 제공하여 향후 게임을 푸시할 필요가 없고 FontTexture를 영원히 사용할 수 있도록 하는 것입니다.

UILabel에 기능 추가

    private static void DynamicFontBrokenFix(Font fnt)
    {
        if(fnt==null)
        {
            return;
        }
 
        if(fnt.characterInfo.Length<500)
        {
            string tmpStr = Resources.Load<TextAsset>("DynamicFontBrokenFix").text;
            fnt.RequestCharactersInTexture(tmpStr, 32);
        }
    }


그런 다음 글꼴을 설정할 때 호출

protected void SetActiveFont (Font fnt)
{
    if (mActiveTTF != fnt)
    {
        if (mActiveTTF != null)
        {
            int usage;
 
            if (mFontUsage.TryGetValue(mActiveTTF, out usage))
            {
                usage = Mathf.Max(0, --usage);
 
                if (usage == 0)
                {
                    mActiveTTF.textureRebuildCallback = null;
                    mFontUsage.Remove(mActiveTTF);
                }
                else
                {
                    mFontUsage[mActiveTTF] = usage;
                }
            }
			else
            {
            	mActiveTTF.textureRebuildCallback = null;
            }
		}
 
		mActiveTTF = fnt;
        DynamicFontBrokenFix(mActiveTTF);
 
		if (mActiveTTF != null)
		{
			int usage = 0;
 
			// Font hasn't been used yet? Register a change delegate callback
			if (!mFontUsage.TryGetValue(mActiveTTF, out usage))
				mActiveTTF.textureRebuildCallback = OnFontTextureChanged;
#if UNITY_FLASH
			mFontUsage[mActiveTTF] = usage + 1;
#else
			mFontUsage[mActiveTTF] = ++usage;
#endif
		}
	}
}


DynamicFontBrokenFix는 게임의 모든 문자를 저장하는 텍스트입니다.
http://blog.csdn.net/huutu http://www.liveslives.com에서 전송됨

FontTexture가 여러 번 생성되는 것을 방지하기 위한 최적화 지점이기도 합니다.

 

[출처] https://blog.csdn.net/huutu/article/details/61923191

 

NGUI UILabel 文字破碎__Captain的博客-CSDN博客

项目使用NGUI,最近碰到 Loading界面的提示文字破碎的Bug。 参考了以下文章 http://blog.csdn.net/langresser_king/article/details/22095235 转自http://blog.csdn.net/huutu http://www.liveslives.com 下面先来了解一下为什么会

blog.csdn.net

 

반응형
Posted by blueasa
, |

Re: UI Label line count

« Reply #5 on: July 19, 2013, 07:04:08 PM »

Just count instances of '\n' in the UILabel.processedText

 

 

[출처] www.tasharen.com/forum/index.php?topic=4509.0

 

UI Label line count

how can i get the total number of lines which will be required to show the label if it is limited with max line count. i will try and explain this more suppose i have a label which has suppose 40 lines, now to make label look small i set the Max Line var f

www.tasharen.com

 

[참조] devkorea.co.kr/bbs/board.php?bo_table=m03_qna&wr_id=42437

 

데브코리아

한국 게임개발자 커뮤니티

devkorea.co.kr

 
반응형
Posted by blueasa
, |

[링크]

https://carrotclub.tistory.com/entry/NGUI-%EC%82%AC%EC%9A%A9-%ED%9D%90%EB%A5%B4%EB%8A%94-%EB%AC%B8%EC%9E%90%EC%97%B4-%EB%A7%8C%EB%93%A4%EA%B8%B0

 

NGUI 사용 흐르는 문자열 만들기

가. 흐르는 문자열 만들기 - 사용 조건 : NGUI가 있어야 함. 나. 코드 - NGUI UILabel.cs 파일내에 있는 overflow enum 값에 FlowText 라는 값을 추가해준다. 해당 옵션이 되어져 있을 경우 글자가 흐르게 할 예정..

carrotclub.tistory.com

 

반응형
Posted by blueasa
, |

1、可以使用BBCode标记

[b]Bold[/b]                      粗体
[i]italic[/i]                         斜体
[u]underline[/u]               下划线
[s]strikethrough[/s]         删除线
[sub]sub[/sub]               下标
[sup]sup[/sup]               上标
[00ff00]设置颜色[-]           设置显示颜色

[url=http://www.cnblogs.com/mrzivchu/][u]博客[/u][/url] 链接

例如设置颜色:

UILabel的Text内容为:[99ff00]n[-]gui: tools

展示效果则为:

这里主要说一下设置连接:

单单的在UILabel的Text里面写入这个是不够的:[url=http://www.cnblogs.com/mrzivchu/][u]博客[/u][/url] 链接

点击是不会产生效果的,我们还要为此UILabel添加一个Collider和一个脚本

脚本如下:

 

 void OnClick()
    {
        UILabel lbl = GetComponent<UILabel>();
        string url = lbl.GetUrlAtPosition(UICamera.lastWorldPosition);
        Application.OpenURL(url);
    }

 

脚本中的OnClick方法要想被触发,就必须要添加一个Collider,这个道理我想大家都懂得!

但要注意一点,假如UILabel的Text内容为:请点击[url=http://www.cnblogs.com/mrzivchu/]我的博客[/url]进入,欢迎大家来批评指正!

我只想点击《我的博客》四个字才去打开连接,而不是点击上面的任何字都可以打开连接,假如上面的文字尺寸是700x40,而《我的博客》四个字的尺寸是200x40,这时我们就可以设置Collider的Center和Size属性来设置点击的区域大小以满足我们的需求,可是当我运行程序的时候Center和Size会自动变为700x40,原来UILabel的Widget有个选项Collider,这个auto-adjust to match表示Collider大Size大小自动匹配为UILabel的Size大小,我们只要把这个勾取消即可!

如果你不想使用BBCode,那么UILabel有个选项BBCode,不勾选的话,就表示不使用BBCode

2、使用图片

我们只要在UILabel的Text里面写了:zwh:) 那么就会出现了一个笑脸图片:

 

为什么会这么神奇呢,原因在于你选择的Font,此处我选择的Font是Arimo20

Arimo20有三个关联的文件:

类型依次为:tga,prefab,txt

这时,我们点击类型为prefab文件,在Inspector窗口的UIFont可以看到

其中可以看到我们熟悉的 :) 笑脸标记,我们这时点击笑脸对应的Emotion - Smile ,展现出来的就是那个笑脸图片,而这个笑脸图片是存在Wooden Atlas图集里面的,如果我们想用其他图片的话,我们可以向Wooden Atlas图集里面增加我们需要展现的图片,然后在下面填写一个约定好的标记,类似于 :) 这样的标记,选择我们想要展现的图片,Add即可,图片的尺寸最好是20x20,以保证和文字上下在一条水平线上!

UILabel的Text为:zwh(bird)zwh 

显示为:

因为我的图片是60x60的,所以和文字上下不一样齐了,这也是我为什么建议图片尺寸是20x20的原因了!

另外说一个问题,我也不知道是不是存在的bug

此处我们为UIFont选择的图集是Wooden Atlas,Sprite是Arimo 20,Arimo 20大概对应的是字符格式,如果此时我们点击Sprite,将会弹出Wooden Atlas里面包含的所有sprite精灵,当我们点击Arimo 14或者Arimo 18的话,那么应用此Arimo20的UILabel将会变形:

原本是这样的:,变成了这样:

 

为Sprite选择Arimo20已经还原不会来了,还是会变形!

解决方案:

就是点击UIFont下的Import Data,也就是导入和Arimo20关联的三个类型(tga,prefab,txt)的文件中的txt文件即可!从而使Arimo的字符集格式还原回来!

另外:

UILabel还有一个Symbols选项,他有三个值:None,Normal,Colored,选择None,那么以 :) 这样形式显示的图片将不会展示,选择Normal(默认)将正常展示,选择Colored,那么图片将会被UILabel下的Color Tint所选择的颜色遮盖!其实这个Color Tint是对文字进行着色的,选择Colored那么也就是意味着图片也和文字应用同样的颜色!

其他属性

overflow:

1.ShrinkContent,总是显示所有文字,根据当前的width和height进行缩放
2.ClampContent,一看到Clamp就想起Clamp函数,也就是不管文本多少个字,根据当前的width和height来显示,超出部分 
不显示
3.ResizeFreely,会对当前的文字长度和行数来调整,UILabel的width和height,基本上是只在一行显示,超出的部分不显示
4.ResizeHeight,保持宽度不变,必要时增加高度。


Spacing :

X:设置字与字之间到间隔,可以为负数,设置得当可以反序

Y: 设置行与行之间的间隔。


Gradient :

设置 渐变字

Max Lines:

用来控制最多要多少行。用0表示不限制。如果设置成n的话,那么超过n的行的文字将不会显示!

 

实现动态文字展现的效果:

先上效果图:

 

层次:

content显示的是文字

bg显示是背景图(uisprite)

title是标题

第一步:先给content添加UIlabel和typewriter effect脚本:此脚本选项的解释如下:

chars per second:每秒显示多少个字符

fade in time:淡入时间

delay on period:延迟期

delay on new line:开始新行延迟时间

scroll view:需要指定scroll view

keep full dimentions:保持全部尺寸

第二步:

设置content组件uilabel的overflow(溢出方式)为ResizeHeight

第三步:

typewriter effect脚本的keep full dementions不要勾选,其他的默认即可

第四步:

设置bg背景图的UISprite的Anchors的Type为Unified(统一),Execute为OnUpdate,Target为mylabel即可!

Anchors的功能是:

物体A相对于所指定物体B的位置设置情况。可以设置离指定物体的上,下,左,右的偏移值,从而实现对齐,主要用在动态的效果的情况下,例如上面的title的位置就是相对于content而设置的,随着content文字的动态增加,title的位置也在不断的上移,实现对齐,避免位置错乱!这大概就是设置Anchors的好处吧!

这里我的title的anchors里面,只要设置了top+50即可,保持与content的顶部的距离即可,其他的可以不用设置!

target为指定物体B,而bg就是A,Execute指在更新时还是可用时去执行,type表示统一的还是高级的


출처 : http://www.cnblogs.com/MrZivChu/p/UILabel.html

반응형

'Unity3D > NGUI' 카테고리의 다른 글

NGUI: Symbols & Emoticons  (0) 2015.02.12
NGUI Emoticons  (0) 2015.02.12
Coloring individual characters in an NGUI UILabel text  (0) 2014.12.31
NGUI UILabel Reference  (0) 2014.12.31
NGUI UILabel BBCode  (0) 2014.12.31
Posted by blueasa
, |

For the game project that I'm currently working on, I needed to find an easy way to color individual characters in the text of an NGUI UILabel.

Fortunately, the solution is pretty simple. When the supportEncoding boolean field on a UILabel is set to true, the text supports color encoding in the[RRGGBB] format.

This means that we can have write text such as the following (the [-] is used to revert to a previous color):

[FF0000]Red[-] [00FF00]Green[-] [0000FF]Blue[-]



The reason I needed to do this was because we want the leading zeros in the Score UILabel to have a different colour than the actual score. And for that, I wrote this neat little method to format my current score to a string with a predefined number of leading zeros and then color those leading zeros independent from the main colour of the label text.

1
2
3
4
5
6
7
8
9
10
11
12
private string FormatScore(int score, string leadingZerosRGBColor, int totalDigits)
{
    var scoreString = score.ToString(CultureInfo.InvariantCulture);
    var zeros = totalDigits - scoreString.Length;
    if (score == 0)
    {
        scoreString = String.Empty;
        zeros++;
    }

    return String.Format("[{0}]{1}[-]{2}", leadingZerosRGBColor, new string('0', zeros <= 0 ? 0 : zeros), scoreString);
}



[출처] http://blog.dreasgrech.com/2013/05/coloring-individual-characters-in-ngui.html

반응형

'Unity3D > NGUI' 카테고리의 다른 글

NGUI Emoticons  (0) 2015.02.12
NGUI UILabel로 Emoticon 넣기..  (0) 2015.02.12
NGUI UILabel Reference  (0) 2014.12.31
NGUI UILabel BBCode  (0) 2014.12.31
PSD Layers to PNG Files(PSD2PNGs)  (0) 2014.12.31
Posted by blueasa
, |

NGUI UILabel Reference

Unity3D/NGUI / 2014. 12. 31. 14:40

Overview

UILabel is a Widget that can be used to display text.



All labels require a Font to work with. This font can be Dynamic (directly referencing a Unity Font), or it can be a Bitmap font -- a font embedded within an Atlas. Dynamic fonts are more robust as they don't require you to pre-generate your glyphs before hand, but Bitmap fonts can be drawn within the same draw call as the rest of your atlas, and can be decorated nicely in an image editing tool such as Photoshop.

You can change the alignment of the labels simply by switching the Pivot point. Top-left, Left and Bottom-left pivot point will result in a left-aligned text. Top, Center, or Bottom alignment will cause the text to be centered, and Top-right, Right or Bottom-right pivot will make your text right-aligned.

With the Dynamic font chosen you can set the Font Size as well as style directly on your label. You can also set the material that will be used to draw it, if you wish.

The big box is -- as you probably guessed -- where you enter text. It's a multi-line text box by default, unless limited by the Max Lines property below it.

Overflow handling lets you determine what happens when the label's text exceeds the allowed space.


  • Shrink Content means the content will be automatically shrunk to best fit the area. It works in conjunction with the Keep Crisp setting if you are using a Dynamic font, making the font size shrink down, not just scaling the content. This results in crisp labels regardless of whether they were shrunk or not.
  • Clamp Content simply means that if the text doesn't fit, it will be cut off.
  • Resize Freely option will make the label's dimensions controlled by the text entered in the field. You won't be able to resize the dimensions yourself.
  • The last option, Resize Height will add grow the height as necessary, but will keep the width constant.

The Spacing field lets you adjust the distance between characters. Both positive and negative values are allowed. This value is in pixels.

Max Lines, as mentioned earlier, lets you control how many lines you want there to be at maximum. You can leave it at zero if you want it to be unlimited.

You can turn off Encoding if you don't want color tags and emoticons to be processed. Input fields do this by default.

If you want, you can give your labels a Gradient by specifying the bottom and top colors.

You can give your text a shadow or an outline Effect, but note that doing so will double the geometry in case of shadow, and multiply it by a factor of 5 in case of outline -- so be mindful of this feature. The Distance parameter controls how far the shadow or outline is from the base text, in pixels.

To change the label's text at run-time, you can do the following:

Code: [Select]
UILabel lbl = GetComponent<UILabel>();
lbl.text = "Hello world!";


Pro-Tip #1

You can add bold, italic, underline, and other effects to your label by using bbcode syntax like so:

[b]bold[/b]
[i]italic[/i]
[u]underline[/u]
[s]strikethrough[/s]

You can also embed clickable links in your labels like so:

[url=Some Message or Link]Click Me[/url]

To retrieve what you clicked on, attach a box collider to your label (ALT+SHIFT+C) and a script that has a function like this in it:

Code: [Select]
void OnClick ()
{
    UILabel lbl = GetComponent<UILabel>();
    string url = lbl.GetUrlAtPosition(UICamera.lastWorldPosition);
    Debug.Log("Clicked on: " + url);
}


Pro-Tip #2

You can give your labels a beveled look by specifying a dark foreground color and a bright Shadow effect.



Pro-Tip #3

You can make the text ignore the label's color tint by using the [c]text here[/c]tag, and change the alpha by using [Aa] syntax, like "[7f]".

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_label.html


출처 : http://www.tasharen.com/forum/index.php?topic=6706.0

반응형

'Unity3D > NGUI' 카테고리의 다른 글

NGUI UILabel로 Emoticon 넣기..  (0) 2015.02.12
Coloring individual characters in an NGUI UILabel text  (0) 2014.12.31
NGUI UILabel BBCode  (0) 2014.12.31
PSD Layers to PNG Files(PSD2PNGs)  (0) 2014.12.31
PSD Layers to 2D Tool Kit(PSD2TK2D)  (0) 2014.12.31
Posted by blueasa
, |

NGUI UILabel BBCode

Unity3D/NGUI / 2014. 12. 31. 14:15

The use of Unity3d NGUI (two) (UILabel Chinese font and click on the font)

Unity3d NGUI can create font can click effect, click on the open web links

There are Chinese font display, can direct call system built-in fonts, does not need the third party font support


UILabel (Script parameters)


The first font options, NGUI is using a static font, when we need to show Chinese, it is best to use dynamic fonts, or you can create static font set

Font Size: font size

Material: The font textures, such as the need for font color

Text: Display content

Overflow: Filler content options, 1, ShrinkContent (content based filling) 2, ClampContent (in the font for the base shear)

3, ResizeFreely (content as the base level for filling) 4, with content high as reference for filling

Alignment: Alignment, font

Keep crisp: Dynamic font sharpening

Gradient: Font change

Effect: The fonts

Spaceing: Font spacing

Max Lines: The number of rows to display font

BBCode: Use the NGUI custom formatting font font


1, Create Chinese font

A. first creates a UILabel in Widget Tool

B. in the NGUI inspector window, select Unity UILabel, then select Font-Arial

C. We are now using dynamic fonts, can display Chinese


2, Create a link font

A. need to add the click event UILabel add a Script

	void OnClick ()
	{
		UILabel lbl = GetComponent<UILabel>();
		
		if (lbl != null)
		{
			string url = lbl.GetUrlAtPosition(UICamera.lastHit.point);
			if (!string.IsNullOrEmpty(url)) Application.OpenURL(url);
		}
	}

The B. for the current UILabel add a Box Collider, adjust the Box Collider size for the current UILabel window size 

The Is Trigger option is on the hook


C. NGUI currently supports formatting font three, 1 ([b]bold[/b] display effect dynamic font changes) 2 ([u]underline[/u] underline

[s]strikethrough[/s] Delete line) 3 ([url=http://www.tasharen.com/][u]clickable hyperlinks[/u][/url] add a web link)


Show all formatting, click clickable to open the link



The use of Unity3d NGUI (two) (UILabel Chinese font and click on the font)


출처 : http://www.programering.com/a/MTO2gDNwATU.html

반응형

'Unity3D > NGUI' 카테고리의 다른 글

Coloring individual characters in an NGUI UILabel text  (0) 2014.12.31
NGUI UILabel Reference  (0) 2014.12.31
PSD Layers to PNG Files(PSD2PNGs)  (0) 2014.12.31
PSD Layers to 2D Tool Kit(PSD2TK2D)  (0) 2014.12.31
PSD Layers to NGUI(PSD2NGUI)  (0) 2014.12.31
Posted by blueasa
, |