Unity——Scroll View 滑动居中、居中的放大、其他的缩小(支持横竖Scroll View)

一、效果

二、上代码,两种方式。

(第一种是在Update中用插值完成的,如果不想再项目中看到Update,下面的另一种改了一段用DoTween实现的,需要导入一下DoTween)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public enum ScrollDir
{
	Horizontal,
	Vertical
}

public class CenterOnChild : MonoBehaviour, IEndDragHandler, IDragHandler, IBeginDragHandler
{
	public ScrollDir Dir = ScrollDir.Horizontal;

	/// <summary>
	/// 是否正在居中
	/// </summary>
	private bool _isCentering = false;

	[Header("居中过程移动速度")]
	public float MoveToCenterSpeed = 10f;
	[Header("中心点放大倍数")]
	public float CenterScale = 1f;
	[Header("非中心点放大倍数")]
	public float UnCenterScale = 0.9f;
	private ScrollRect _scrollView;

	private Transform _content;

	private List<float> _childrenPos = new List<float>();
	private float _targetPos;

	/// <summary>
	/// 当前中心child索引
	/// </summary>
	private int _curCenterChildIndex = -1;

	/// <summary>
	/// 当前中心ChildItem
	/// </summary>
	public GameObject CurCenterChildItem
	{
		get
		{
			GameObject centerChild = null;
			if (_content != null && _curCenterChildIndex >= 0 && _curCenterChildIndex < _content.childCount)
			{
				centerChild = _content.GetChild(_curCenterChildIndex).gameObject;
			}
			return centerChild;
		}
	}
	/// <summary>
	/// 根据拖动来改变每一个子物体的缩放
	/// </summary>
	public void SetCellScale()
	{
		GameObject centerChild = null;
		for (int i = 0; i < _content.childCount; i++)
		{
			centerChild = _content.GetChild(i).gameObject;
			if (i == _curCenterChildIndex)
				centerChild.transform.localScale = CenterScale * Vector3.one;
			else
				centerChild.transform.localScale = UnCenterScale * Vector3.one;
		}
	}
	void Awake()
	{
		_scrollView = GetComponent<ScrollRect>();
		if (_scrollView == null)
		{
			Debug.LogError("ScrollRect is null");
			return;
		}
		_content = _scrollView.content;

		LayoutGroup layoutGroup = null;
		layoutGroup = _content.GetComponent<LayoutGroup>();

		if (layoutGroup == null)
		{
			Debug.LogError("LayoutGroup component is null");
		}
		_scrollView.movementType = ScrollRect.MovementType.Unrestricted;
		float spacing = 0f;
		//根据dir计算坐标,Horizontal:存x,Vertical:存y
		switch (Dir)
		{
			case ScrollDir.Horizontal:
				if (layoutGroup is HorizontalLayoutGroup)
				{
					float childPosX = _scrollView.GetComponent<RectTr
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值