Unity之UGUI——大图翻页——UI适配不同分辨率

先看效果:

结构:

代码:

using DG.Tweening;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Page1_Index : MonoBehaviour, IPointerExitHandler
{
    private ScrollRect scrollView;
    private RectTransform content;
    private int pageMaxIndex = 3;
    private int currentIndex = 0;
    private bool isComponentsInited = false;
    private bool isStarted = false;
    private int screenWidth = 1920;

    public void OnPointerExit(PointerEventData eventData)
    {        

        float deltaX = screenWidth * 0.1f;

        if (currentIndex == 0)
        {
            if (content.anchoredPosition.x < -deltaX)
            {
                currentIndex = 1;
            }
        }
        else if (currentIndex == pageMaxIndex)
        {
            if (content.anchoredPosition.x > -screenWidth * currentIndex + deltaX)
            {
                currentIndex--;
            }
        }
        else
        {
            //处理大于2张的情况
            if (content.anchoredPosition.x > -screenWidth * currentIndex + deltaX)
            {
                currentIndex--;
            }
            else if (content.anchoredPosition.x < -screenWidth * currentIndex - deltaX)
            {
                currentIndex++;
            }
        }

        int targetX = -currentIndex * screenWidth;

        content.DOAnchorPosX(targetX, 0.5f);
    }

    private void Start()
    {       
        scrollView = transform.Find("ScrollView").GetComponent<ScrollRect>();
        content = transform.Find("ScrollView/Viewport/Content").GetComponent<RectTransform>();
        isComponentsInited = true;

        content.anchoredPosition = Vector2.zero;
        currentIndex = 0;
        isStarted = true;
    }

    private void OnEnable()
    {
        if (isComponentsInited && !isStarted)
        {
            content.anchoredPosition = Vector2.zero;
            currentIndex = 0;
            isStarted = true;
        }
    }

    private void Update()
    {
        if (content.anchoredPosition.x > 0)
        {
            content.anchoredPosition = Vector2.zero;
        }
        else if (content.anchoredPosition.x < -screenWidth * pageMaxIndex)
        {
            content.anchoredPosition = new Vector2(-screenWidth * pageMaxIndex, 0);
        }
    }
}

适配注意事项:

1.canvas设置

 

2. screenWidth = 1920,即这里就等于canvas里设置的屏幕宽度,而不能在start函数里动态获取屏幕宽度:screenWidth = Screen.Width,我就踩了这个坑,自以为是适配不同分辨率,但恰恰相反

3. 所有位置判断和移动的距离,都依据1920这个值(制作分辨率宽度)

 

不得不说Unity的UGUI分辨率适配做得的确简介,一次开发,多屏适配,给它点个赞

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值