Unity3d学习笔记 UGUI锚点屏幕自适应问题

来源:互联网 发布:腾讯云和阿里云的区别 编辑:程序博客网 时间:2024/05/22 05:31

此方法只适用于Canvas的Render Mode 为 Screen Space - Overlay

  1. 如下图所示设置,将Pivot 设置为0,0 并以左下角为原点
    这里写图片描述
  2. 这样PosX 和 PosY 就是 0 ,这样就不会随着屏幕大小比例的变化而使得有些图片显示不全会不能铺满
  3. 接着写个脚本,根据当前屏幕的长和宽,与当前UI的Width和Height进行等比例转换即可。
  4. 在这贴一个Width和Height颠倒的~正的自己想,很简单,哈哈。
using UnityEngine;using System.Collections;// 注意 此脚本适用于长宽颠倒public class SpriteChangePixel : MonoBehaviour {    public float width = 1080;    public float height = 1920;    // Use this for initialization    void Start () {        float w = (float)Screen.width / width;        float h = (float)Screen.height / height;        RectTransform rectRra =this.GetComponent<RectTransform>();        if (rectRra != null) {            Vector3 pos = rectRra.localScale;            pos.x *= h;            pos.y *= w;            rectRra.localScale = pos;            Debug.Log(pos);        } else {            Vector3 pos = transform.localScale;            pos.x *= h;            pos.y *= w;            transform.localScale = pos;            Debug.Log(pos);        }        Destroy (this);    }}
原创粉丝点击