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

카테고리

분류 전체보기 (2737)
Unity3D (817)
Script (91)
Extensions (14)
Effect (3)
NGUI (77)
UGUI (8)
Physics (2)
Shader (36)
Math (1)
Design Pattern (2)
Xml (1)
Tips (200)
Link (22)
World (1)
AssetBundle (25)
Mecanim (2)
Plugins (70)
Trouble Shooting (68)
Encrypt (7)
LightMap (4)
Shadow (4)
Editor (8)
Crash Report (3)
Utility (9)
UnityVS (2)
Facebook SDK (2)
iTween (3)
Font (11)
Ad (14)
Photon (2)
IAP (1)
Google (8)
Android (45)
iOS (41)
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-28 00:03

약 2~3 주 전 빌드를 하다 보니 apk 파일 용량이 50MB 가 넘어가는 상황이 벌어졌다....

(google 정책상 50 MB가 넘어가면 안된다고 한다 )

느낌표


당장 내일이 업데이트라 급한대로 부랴부랴 별로 티 가 나지 않는 아이콘 이미지들의 크기를 줄여서


빌드를 해서 간신히 50MB 이하로 줄이긴 했지만


앞으로 추가적인 콘텐츠에 의해 이미지 들이 추가 될 시에 같은 문제가 발생할거 같기에 


대처방안이 필요했다.


대부분의 리소스 파일들은 CDN 서버에서 다운 받아 사용하는 방식을 쓰고 있으니

제일 큰 용량을 차지하는 Atlas 파일들 또한 CDN 서버에서 다운 받아 로드 하는 방식으로 변경하면

될거 같기에 구글링을 시작 하였다. 


찾아 보니 의외로 간단 하였다


Unity Pro 에서는 assetbundle 파일을 만들기 및 로드하기가 된다고 한다 (Unity Basic 버전에서는 안된다고 한다 실제 테스트 는 해보진 않았다 ) 


1.스크립트 작성 (AssetBundle Create)



Atlas 가 있는 프로젝트 내부에 위와 같은 스크립트를 넣기만 하면 

유니티 상단의 메뉴 바에  Export 라는 항목이 생길것이다 



2. AssetBundle 생성하기 


그 다음은 프로젝트 뷰에 있는 아틀라스를 선택후 상단의 새로만든 Export메뉴를 눌러서

저장할 위치를 정하고 저장을 누르면 AssetBundle 이 생성된다

이때 중요한건 Atlas는 3가지로 구성되어 있따 GameObject(Prefab), Material, Texture 로 이루어져있는대

AssetBundle을 만드는건 GameObject만 선택한 상태로 만들면된다. 

또한 각각 GameObject , Material, Textture 의 이름은 달라야 한다 . 


예를들어 Atlas_Test_go, Atlas_Text_mat, Atlas_Test_tex, 이런식으로 이름을 다르게 해야 한다 이름이 같으면 잘안된다는대 이는 직접해보진 않고 처음부터 따로 이름을 바꾼뒤 어셋번들을 생성하였기에 이것은 궁금 하신분은 직접 해보도록..


또한 GameObject가 아닌 Material 이나, Texture로만 Assetbundle을 뽑아서 로드 하려고하면 실제 궁극적으로 필요한 Ngui의 UIAtlas 라는 객체가 없어서 필요한 Sprite에 Atlas를 세팅할수 없다.


GameObject 만 AssetBundle 을 생성하여도 AssetBundle 을 뽑는 함수의 옵션 때문인지 하위의 정보들도 같이 합쳐져서 만들어 지는 거 같다. 실제로 해당 파일을 로드할때 디버깅을 하면서 보니 로드된 목록에 Texture 와 Material이 포함되어 있었다.



3. Atlas 를 로드 해보자.





당연 하지만 위 소스 중에 _resourcepath 는 실제 AssetBundle 파일이 있는 장소여야 한다. 해당 경로에서 해당 확장자를 가진 ( 확장자를 .dp로 하였기에 해당 확장자를 긁어 모았다 ) 

읽어 들인뒤 로드하였다 이떄 ab.Load() 함수를 사용하였는대 AllLoad()를 사용하게 되면 해당 파일의 어떤 것들이 담겨져 있는지 보이는대 이를 디버깅으로 까보면 확실히 기억은 안나지만 5~6개의 파일들이 담겨져 있던걸로 기억한다.


하지만 우리가 필요한건 Atlas GameObject 이기에 typeof(GameObject)로 골라내어 로드한후 해당 Gameobjcet 의 UIAtlas  객체를 뽑아내어 Atlas 목록에 넣고 있다. 


4. Load  한 Atlas 적용하기.




이제 우리가 마지막으로 원하는건 로드한 Atlas 를 써먹는거다 .

위와 같은 간단한 소스를 만들어서 Sprite 에 넣어주면 해당 Sprite 가 Awake 될때 

에디터상의 세팅된 AtlasKind에 따라 자기 자신의 Atlas 를  세팅하고 Sprite 이미지 까지 

지정된 이름으로 세팅한다.



 - 잡소리


이러한 Atlas 를 외부에서 로드해서 사용하는 것들은 이미지들이 더 추가될 가능성이 낮고 

또한 실제 이런 이미지들을 사용하는 것들이 런타임 도중 동적으로 이미지가 바뀔 가능성이 

낮은 것들을 위주로 하였기에 ( 또한 아틀라스가 로딩 되기전에 보여지는 이미지가 아닌 것들 )

Awake 함수에서 한번 로드된 아틀라스 로 자기 자신의 아틀라스와 이미지를 세팅하고

끝내는 방식으로 하였다


당연히 아틀라스를 로드 하기전에 보여져야 되는 이미지들은 이런식으로 하면안된다

(로고라던지, 로딩 화면이라던지)


또한 이미지가 런타임 도중 계속 바뀌어야 하는 것들 인벤창의 아이템 이라 던지...

이런 것들은 이미지가 추가될 가능성도 높고 이미지들이 바뀌거나 세팅 되거나 하기전에 가장먼저

Atlas가 세팅되어야 하므로 ( 아틀라스가 세팅되기전의 해당 Sprite의 이미지를 바꾸거나 한다면...

Error가 나던가..? 아마 안나긴 할거다 하지만 아무런 이미지도 보이지 않을거다 ) 

신경써야 되는 부분이 더 생길거 같기도 하고 아이템아이콘 같은경우 사용하는 부분이 너무 많아 그런 여러곳을 전부다 찾아가며 테스트 해보기 귀찮아서 


간단하고 바뀔일 없고 이미지는 커서 용량을 많이 차지하는 것들 로 해당 작업을 하였다.


위의 소스들을 그대로 쓴다면 아마 안될거다(Export스크립트 제외 ) 

그러니 안되는건 레퍼런스를 참조해보도록.... 




출처 : http://chocotart.tistory.com/entry/NGUI-Atlas-Assetbundle-%EB%A7%8C%EB%93%A4%EA%B8%B0-%EB%B0%8F-%EB%A1%9C%EB%93%9C-%ED%95%98%EA%B8%B0

반응형
Posted by blueasa
, |

 

 

[기존 소스에 일부 코드 수정]

CUIListView.cs
0.03MB

 

 

스크롤뷰 아이템을 재사용 할 수 있게 해주는 스크립트 입니다.

인터넷에 이미 몇가지 있는 걸로 알지만, 제가 쓰고 있는 것도 공유해 봅니다.

 

사용법은 간단합니다.

스크립트에 멤버 변수로 CUIListView를 등록하면 다음과 같이 나옵니다. 

 

 

Item List - 스크롤뷰가 포함되어 있는 오브젝트.

Item - 리스트로 출력할 프리팹.

Add Row of Column - 0일 경우 View사이즈에 딱 맞게 아이템을 생성해줍니다. 이렇게 되면 아이템 재사용이 제대로 동작하지 않으니, 1이나 2로 지정합니다.

Item Padding - 아이템 사이의 간격입니다. 알아서 다 맞춰주기 때문에 Grid 사용하지 않아도 됩니다.

Scrollbar - 스크롤바가 있을경우 지정해줍시다.

그리고 UIPanel의 offset과 Center 좌표는 0으로 두는게 좋습니다. 패널 위치를 옮기려면 게임오브젝트의 좌표를 움직이는게 좋습니다.


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

public class CListViewTest : MonoBehaviour
{
    public CUIListView m_ListView;

    private List m_ItemList = new List();

    void Start ()
    {
        for(int i = 0; i < 500; ++i)
        {
            m_ItemList.Add(i);
        }

        m_ListView.OnUpdateItem = OnUpdateItem;
        m_ListView.OnGetItemCount = OnGetItemCount;

        m_ListView.Init();
    }

    public void OnUpdateItem(int index, GameObject go)
    {
        CListViewTestItem item = go.GetComponent<CListViewTestItem>();
        item.m_Label.text = index.ToString();
    }

    public int OnGetItemCount()
    {
        return m_ItemList.Count;
    }
}

public class CListViewTestItem : MonoBehaviour
{
    public UILabel m_Label;
}

 

코드는 위와같이 작성합니다. 

OnUpdateItem - 아이템이 갱신될 때 호출됩니다. 나머지 부분은 직접 구현하시면 됩니다. 

OnGetItemCount - 리스트의 전체 개수가 필요할 때 호출됩니다.

추가로 Refresh와 Reset, SetFocus 함수가 있는데 필요에 따라서 호출하여 쓰시면 될 것 같습니다.

 

미구현 기능 및 버그

- 스크롤 바를 클릭해서 뷰를 이동하는 기능. 이 기능을 쓸일이 없고 작업하기도 힘들어서 구현하지 않았습니다.

- 아이템이 한페이지 이상 삭제되었을 경우에 Refresh를 호출하면 뷰 이동이 안되는 버그. (이런 경우에는 Reset을 쓰는 걸 추천).

2015. 4. 15 업데이트

아이템이 리스트에 딱 맞게 설정되어 있을 경우에 스크롤이 되는 버그가 있어서 수정하였습니다.

 

2015. 5. 26 업데이트

아이템의 크기가 뷰사이즈 보다 작을 경우 드래그가 불가능 하도록 스크롤뷰를 disable 시키는 기능 추가.

SetFocus(0); 을 호출 할 경우 0번째 아이템이 화면 중앙에 위치하는 버그 수정.

 

출처 : http://kheldon.tistory.com/2

 

반응형
Posted by blueasa
, |

NGUI를 이용해서 UI 제작을 하면서 UI 디자이너에게서 리소스와 배치 데이터를 받아서 작업을 하는 데,


유니티 특성상 UI는 트리노드 구조를 가져서 특정 UI의 좌표가 어떤지 알기가 힘들어서 쉽게 보기 위해 대충 만들어 봤다.


당장 그냥 쓰기 위해 위치나 색깔등 대충해서 만들기..


따로 넣기도 귀찮아서 그냥 NGUI 소스인 UIWidget.cs에 추가 했다.


P.s. UI디자이너가 포토샵을 보통 쓰기때문에 NGUI가 데카르트 좌표계를 쓰고 있지만 UI디자이너가 주는 정보와 매칭되게 하기 위해서 스크린좌표계로 변환해서 보여주도록 했음.



public class UIWidget : UIRect
{
    ....
    void OnDrawGizmos ()
    {
        .....
#if UNITY_EDITOR
        // 아래 추가한 함수를 여기서 실행.
            ShowSelectedUICoordinate();
#endif // UNITY_EDITOR
    }

#if UNITY_EDITOR  // 에디터에서만 실행하도록..
    /// 
    /// 선택된 UI의 좌표(X/Y/Width/Height) 보여주는 함수.
    /// 좌표계는 스크린좌표계 기준.
    /// 

void ShowSelectedUICoordinate() { // by blueasa if (UnityEditor.Selection.activeGameObject == gameObject) { // 타겟 해상도(1280x720) 자신이 원하는 해상도에 맞게 변경. float fScreenWidth = 1280f; float fScreenHeight = 720f; Camera cUICamera = UICamera.mainCamera; if (null == cUICamera) { UnityEngine.Debug.LogWarning("Can't find UICamera.."); return; } GUIStyle style = new GUIStyle(); style.normal.textColor = Color.yellow; // UI는 데카르트 좌표계이므로 스크린 좌표계로 변환해서 사용. // X/Y를 Widget 중심으로 사용하기로 해서 수정. 좌측상단 사용하려면 선택하면 될 듯.. #region X/Y Widget 중심(스크린 좌표계) //float fX = cUICamera.WorldToViewportPoint(worldCenter).x * fScreenWidth; //float fY = (1f - cUICamera.WorldToViewportPoint(worldCenter).y) * fScreenHeight; //// X/Y가 Widget의 중심이기때문에 크기가 1/2만 나오므로 원래크기를 만들기 위해 2를 곱함. //float fWidth = ((cUICamera.WorldToViewportPoint(worldCorners[3]).x * fScreenWidth) - fX) * 2f; //float fHeight = (((1f - cUICamera.WorldToViewportPoint(worldCorners[3]).y) * fScreenHeight) - fY) * 2f; #endregion #region X/Y Widget 중심(데카르트 좌표계) float fX = cUICamera.WorldToViewportPoint(worldCenter).x * fScreenWidth; float fY = cUICamera.WorldToViewportPoint(worldCenter).y * fScreenHeight; // X/Y가 Widget의 중심이기때문에 크기가 1/2만 나오므로 원래크기를 만들기 위해 2를 곱함. float fWidth = ((cUICamera.WorldToViewportPoint(worldCorners[2]).x * fScreenWidth) - fX) * 2f; float fHeight = ((cUICamera.WorldToViewportPoint(worldCorners[2]).y * fScreenHeight) - fY) * 2f; #endregion #region X/Y 좌측상단(스크린 좌표계) //float fX = cUICamera.WorldToViewportPoint(worldCorners[1]).x * fScreenWidth; //float fY = (1f - cUICamera.WorldToViewportPoint(worldCorners[1]).y) * fScreenHeight; //float fWidth = (cUICamera.WorldToViewportPoint(worldCorners[3]).x * fScreenWidth) - fX; //float fHeight = ((1f - cUICamera.WorldToViewportPoint(worldCorners[3]).y) * fScreenHeight) - fY; #endregion string strXYWH = string.Format("[X] {0:0.00}, [Y] {1:0.00} [W] {2:0.00}, [H] {3:0.00}", fX, fY, fWidth, fHeight); UnityEditor.Handles.Label(transform.position, strXYWH, style); // 참고.. //Debug.Log("worldCorners[0] " + camera.WorldToViewportPoint(worldCorners[0])); // 좌하(↙) //Debug.Log("worldCorners[1] " + camera.WorldToViewportPoint(worldCorners[1])); // 좌상(↖) //Debug.Log("worldCorners[2] " + camera.WorldToViewportPoint(worldCorners[2])); // 우상(↗) //Debug.Log("worldCorners[3] " + camera.WorldToViewportPoint(worldCorners[3])); // 우하(↘) } } #endif // UNITY_EDITOR }



출처 : Mine


반응형
Posted by blueasa
, |

NGUI를 사용하는 중..

UI 배치를 위해 UI디자이너분이 준 배치정보(x,y,width,height)를 보고 배치하려니

트리 형태로 볶잡하게 묶인 상태로는 월드포지션인 x,y를 기준으로 배치하기가 너무 힘들어서 좀 편하게 해보려고 뻘짓 중..


현재 UIWidget.cs에 추가 및 테스트 중..

UISprite에 들어가야될까 싶다.


void OnDrawGizmos()

{

if (UnityEditor.Selection.activeGameObject == gameObject)

     {

         int iLayer = LayerMask.NameToLayer("UI");

         Camera camera = NGUITools.FindCameraForLayer(iLayer);

         UnityEditor.Handles.Label(transform.position, camera.WorldToScreenPoint(transform.position).ToString());

     }

}




참조 : http://blueasa.tistory.com/1092

참조 : http://blog.csdn.net/liqiangeastsun/article/details/42175199

반응형
Posted by blueasa
, |

NGUI로 여러 해상도 대응 꽉 채우기

(참조 : http://hanamoni.tistory.com)



 1280x720 해상도 기준


[순서]

1) NGUI-UIRoot.cs 열기.


2) Inspector Window 에서 설정.

    Scaling Style - Constrained On Mobiles

    Content Width - 1280 Fit  (Check)

    Content Height - 720 Fit  (Check)


3) UIRoot-Update() 함수에서 아래를 교체

   [원본]

    mTrans.localScale = new Vector3(size, size, size);


   [변경]

    float fX = (NGUITools.screenSize.x / 1280f);

    float fTemp = (720f * fX);

    float fY = NGUITools.screenSize.y / fTemp;

    mTrans.localScale = new Vector3(size, size * fY, size);





[참조 링크의 내용]


NGUI 새로운 버젼.. 


해상도가 안맞아서 해상도에 맞게 늘릴려고 만든. 코드.


UIRoot 에서


기준을 1280 X 720 할때.


Inspector Window 에서 설정.

Scaling Style - Constrained On Mobiles

Content Width - 1280 Fit  Check 

Content Height - 720 Fit  Check



UIRoot 스크립트 에서  변경.



void Update ()  에서.


mTrans.localScale = new Vector3(size, size, size);  < -  이코드를 




float x_value = (screen.x / 1280f);

float temp_value = (720f * x_value);

float y_value = screen.y / temp_value;


mTrans.localScale = new Vector3(size , size * y_value, size );


요렇게 변경하면


기준 1280 x 720 으로 잡고 모든해상도에 맞게 잘 늘어나거나 줄어든다.

반응형
Posted by blueasa
, |

"Infinite Scrolling" for Unity3D Using NGUI's UIScrollView (1st attempt)

For latest update please check this post instead 
I've been using NGUI for UI related work on my Unity project for the past few weeks and it is a breath of fresh air when compared to the stock UnityGUI (OnGUI()).

Part of my project relate to display a relatively large amount of data dynamically (well not very large but in thousands) and instantiating a prefab for each data element didn't seem like a good idea to me :-)

So instead I decided to add some logic to do a scroll view with fixed pool of items that I reuse and position according to the direction of the scroll and get it fed with the correct data. 

Although I am sure that there are existing solutions I decided to do my own.

The logic so far is built using UIGrid with fixed cell height for the moment (not well suited for UITable with different cell height) and the panel is using soft clip. the Scroll view is using momentum only (Spring physics breaks my current logic for some reason)

Initialization steps: 
  1. Pool size is calculated using the cell height against the panel height plus some buffer (currently I am using a buffer of 4 list items)
  2. List items' pool is instantiated with corresponding data from the data list
  3. A map is maintained to keep track of which data item are used in which list items
While Scrolling:
  1. Any item that turns a visible from an invisible state will notify the main controller
  2. We check the direction of the scroll based on which item is visible (e.g. if the next item is visible means that we are dragging upwards)
  3. based on the direction we reuse the items at the top or the bottom of the list accordingly (e.g. if direction is up the top item moves to the bottom and get populated with data from the corresponding data element)

 

 This is a first attempt and further posts will follow as the logic evolve.

==UPDATE==
I am in the process of making this component available as open source.
Meanwhile we've launched a free app on Android that uses it called Avatar Messenger
==UPDATE 2==
 The component is available as open source
https://github.com/OrangeLabsUK/InfiniteList_NGUI



[파일]

InfiniteList_NGUI-master.zip



출처 : http://www.geekyhamster.com/2013/12/infinite-scrolling-for-unity3d-using.html

반응형

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

NGUI UI의 현재 위치 표시하기[수정중]  (0) 2015.05.08
NGUI 다양한 해상도 대응하기  (2) 2015.04.21
NGUI: Symbols & Emoticons  (0) 2015.02.12
NGUI Emoticons  (0) 2015.02.12
NGUI UILabel로 Emoticon 넣기..  (0) 2015.02.12
Posted by blueasa
, |


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


반응형
Posted by blueasa
, |

NGUI Emoticons

Unity3D/NGUI / 2015. 2. 12. 01:16
我也没记清NGUI是哪个版本开始增加了表情这个功能,不过好像是3.0以后的,现在我就来简单的说说如何使用NGUI中新增的这个输入表情的功能的用法。

我们要准备表情图片,去网上随便找些表情来,我这是在百度后经过ps后得到表情,大家也可以自己去网上找下表情的图片,然后自己PS下得到自己所要的。我的如下:

1.png 

我们在这里要注意一下,表情图片最好是20X20大小,因为在外部是修改不了大小的,这个估计是NGUI作者封装在内部了,要去修改内部代码才行的哦。还有一个是如果想输入表情,暂时不支持动态字体的哦。所以得自己用BMFont去制作Bitmap字体。我将我已经制作好的Bitmap字体放进来了,如图:



我们将我们千辛万苦弄来的表情来制作成一个图集吧,待会会用到,我这如下:

3.png 

现在我将BMFont制作好的字体放进NGUI里面,然后用来创建字体图集。大家会发现这里和原来有点不一样了,在Output栏里面多了个Atlas这一栏,这个其实就是表情图集了。我们将我们的表情图集拖放到这一栏就可以了,然后点击创建吧。如图:

4.png 

我们现在来给表情定义特殊字体集合吧,其实就是解析这些定义的文字,然后用表情来代替他们显示,我们选择我们刚才创建的字体,就会发现有这个了:

    6.png 
然后我们点击展开一下,就会把我们的表情和一个特殊文字对应吧。我把一些对应的表情设置的如下:

7.png 

6  好了,现在我们可以来输入我们的自定义的表情了,我输入<:kx (就是开心那个表情对应的特殊字码)  如图:

8.png    9.png 

不要怀疑啊,就是这样简单。  没了。




5.png (13.65 KB, 下载次数: 5)

5.png



转:http://www.narkii.com/club/thread-313296-1.html




반응형
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
, |