unityUI按钮忽略透明部分

1、UI贴图是PNG格式。

2、打开贴图的读写。

3、给代码上添加脚本。

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

namespace JHL
{
	public class Model_ButtonSetting : MonoBehaviour, ICanvasRaycastFilter
	{
		protected Image _image;
		// Start is called before the first frame update
		void Start()
		{
            _image = GetComponent<Image>();

            Texture2D tex = _image.sprite.texture as Texture2D;

            bool isInvalid = false;
            if (tex != null)
            {
                try
                {
                    tex.GetPixels32();
                }
                catch (UnityException e)
                {
                    Debug.LogError(e.Message);
                    isInvalid = true;
                }
            }
            else
            {
                isInvalid = true;
            }

            if (isInvalid)
            {
                Debug.LogError("This script need an Image with a readbale Texture2D to work.");
            }
        }

        public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
        {
            Vector2 localPoint;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(_image.rectTransform, sp, eventCamera, out localPoint);

            Vector2 pivot = _image.rectTransform.pivot;
            Vector2 normalizedLocal = new Vector2(pivot.x + localPoint.x / _image.rectTransform.rect.width, pivot.y + localPoint.y / _image.rectTransform.rect.height);
            Vector2 uv = new Vector2(
                _image.sprite.rect.x + normalizedLocal.x * _image.sprite.rect.width,
                _image.sprite.rect.y + normalizedLocal.y * _image.sprite.rect.height);

            uv.x /= _image.sprite.texture.width;
            uv.y /= _image.sprite.texture.height;

            //uv are inversed, as 0,0 or the rect transform seem to be upper right, then going negativ toward lower left...
            Color c = _image.sprite.texture.GetPixelBilinear(uv.x, uv.y);

            return c.a > 0.1f;
        }
    }//end class
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值