UGUI不规则图片点击事件处理

项目中,有可能会遇到图片不是方形的。比如是圆形的。这个时候,我们希望鼠标点击到圆形的部分,才算点击。点击到方形的空白部分不算点击可能有这样的需求

我们可以按照下面步骤来处理。

原理:

  UGUI在处理控件是否被点击的时候,在检测图片的时候,会调用Image的IsRaycastLocationValid( )方法

  该方法会获取当前图片点击点的透明度,如下代码片段:

try
{
      return sprite.texture.GetPixelBilinear(x, y).a >= m_EventAlphaThreshold;   
}
catch (unityException e)
{
      Debug.LogError("Using clickAlphaThreshold lower than 1 on Image whose sprite texture cannot be read. " + e.Message + " Also make sure to disable sprite packing for this sprite.", this);
      return true;
}

只有当前点击的图片的当前点的透明度超过了设置的m_EventAlphaThreshold阈值。才返回真。返回真的情况下,这个UI控件才表示被点击到。

所以,我们可以来修改这个值。这个值是0-1之间的。

把图片设置成可读写的。

设置好图片之后,来编写代码:

public class test : MonoBehaviour {
    public Image image;
    float threshold = 0.5f;
    // Use this for initialization
    void Start () 
    {
        image.alphaHitTestMinimumThreshold = threshold;    
    }
    
    // Update is called once per frame
    void Update () {
        
    }

    public void OnClick()
    {
        print("点击到了!!!");
    }
}

这样就修改了图片的点击时候,判断是否真的点击到图片内容了。可以过滤掉透明的像素。只有点击到有颜色的地方,才算是真实的点击。

注意:这个方法需要开启sprite的Read/Write Enable属性,这样程序就会在内存中多存一份sprite,内存占用也就翻了一倍,所以这个方法不太适合移动端大量按钮的使用。

还有一种更加简单的办法:

给你不规则的图片挂上PolygonCollider2D组件,并圈出响应范围。

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

public class TestTouch : MonoBehaviour {

    private PolygonCollider2D polygonCollider2D;

    // Use this for initialization  
    void Start()
    {
        polygonCollider2D = GetComponent<PolygonCollider2D>();
    }

    // Update is called once per frame  
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (polygonCollider2D.OverlapPoint(Input.mousePosition))
            {
                Debug.LogError("点击到了");
            }
        }
    }  
}
原文地址:https://www.cnblogs.com/zjw007/p/8651283.html