c# - 统一二维 : Get pixel of color of Raw Image

标签 c# user-interface unity3d color-picker

我想知道如何获得 rawImage 纹理的像素颜色。

这是我的场景:

enter image description here

public class ColorPicker : MonoBehaviour, IPointerClickHandler
{
    public GameObject Cube;

    public void OnPointerClick(PointerEventData eventData)
    {
        if (Input.GetMouseButtonUp(1))
        {
            Vector3 localPosition = transform.InverseTransformPoint(eventData.pressPosition);

            Color color = (GetComponent<RawImage>().texture as Texture2D).GetPixel(Convert.ToInt32(localPosition.x),
               Convert.ToInt32(localPosition.y));
            Cube.GetComponent<Renderer>().material.color = color;
        }
    }
}

如您所见,使用这段代码,它可以工作,但不会被调用。

其实我是够不到蓝色的。我只能得到我方 block 的顶部。

你能帮我如何在我按下右键时获得颜色吗?

谢谢

最佳答案

您使用的鼠标位置

Input.mousePosition 

在屏幕空间中(意味着您获得的位置是相对于屏幕尺寸的)。

你要获取的是鼠标在 Canvas 空间中的位置(相对于 Canvas 大小,所以不用担心 Canvas 大小)。

您可以通过在 ColorPicker 脚本中实现 IPointerClickHandler 来做到这一点(这也是比使用 Input.mousePosition 更好的做法)。

using UnityEngine.EventSystems;    

  public class ColorPicker : MonoBehaviour, IPointerClickHandler{

  public GameObject Cube;

  void OnPointerClick(PointerEventData eventData)
  {
     //eventData.position
     //Vector3 localPosition = transform.InverseTransformPoint(eventData.pressPosition);
     //ignore z coordinate
  }
}

PointerEventData 包含很多有用的信息,您可以在统一文档中获取更多信息https://docs.unity3d.com/ScriptReference/EventSystems.PointerEventData.html

您可能仍需要使用以下方法转换鼠标位置

transform.InverseTransformPoint(eventData.pressPosition);

因为我还没有测试过这个。但我希望这能为您指明正确的方向!

关于c# - 统一二维 : Get pixel of color of Raw Image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41550008/

相关文章:

c# - 在 C# 中按字符拆分字符串

c# - 通过覆盖链的 IEnumerable 列表

c# - 在字符串上调用 .ToString() 来更改其格式

javascript - 在 Kendo UI Scheduler 中隐藏时间行

c# - Unity 网络就绪检查

c# - 如何解构可空元组?

JavaFX 2 TreeView 将焦点从 TreeView TreeCell 更改为

Java - 处理大型 GUI 构造函数的最佳方法?

c# - Mathf.Clamp 在 Unity 3D 中将我的 eulerangle 重置为 minValue

android - 要嵌入 iOS/Android-View 的跨平台 3d 引擎?